Converting a Reader to an InputStream

Is there a way to convert a standard Reader to an InputStream just like you can convert an InputStream to a reader VIA the InputStreamReader class.

Hi,
No, there's no easy way, and it's probably due to the fact that the reader can perform conversions.
You can however read the data from the reader, create a String, get the bytes from the string and use a ByteArrayInputStream.. but it sounds bad. Why do you want to convert from a reader to a stream?
Kaj

Similar Messages

  • Question about read method of InputStream

    Hello everyone,
    I am using read method of InputStream to read a stream from a remote machine. The network connection is not very stable (for example, a wireless network whose the signal strength is relatively low). I am wondering if read method returns -1 (which indicates the end of the stream has been reached), and if I invoke read method again on the same stream, is it possible to read any more data?
    I think maybe I can read some more data even if read returns -1 in one time because the connection is not very stable. I am looking for your comments to my problem in my specific situation.
    regards,
    George

    Thanks Adeodatus,
    Doc says This method blocks until input data is
    available, the end of the stream is detected, or
    an
    exception is thrown.
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputS
    tream.html#read()
    I have not found any related parts in documents.
    http://java.sun.com/j2se/1.4.2/docs/api/
    Them's docs.
    if you're using a different version of java, replace
    the underlined portion with your version number.I am using JDK 1.3, and I have found related documents. But I can not find out where can I set timeout value of read operation. I am reading data from an HTTP InputStream. Can you help?
    regards,
    George

  • How to read out a InputStream from a socket?

    Hei,
    I try to write a programm that should also be accessed via telnet. So I wrote a classe that has a ServerSocket, a Socket, an InputStream and an OutputStream.
    I read out the InputStream via a byte arry, but the inputStream always starts with the first line I entered. How do I empty the Stream? Mark is not supported :(
    So what can I do, to get only the last enty?
    big thx,

    use the other read option, see:[url http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html#read()]InputStream#read
    This allows you to read from an offset.

  • How do I convert a read only word doc to a read only pdf file?

    How do I convert a read only word doc to a read only pdf file?
    Thanks, Linda

    Hi Linda,
    I just tried it, and was able to convert a Word .doc to to PDF, in spite of the fact that it was marked Read Only. Here are the instructions for uploading and converting to PDF with Acrobat.com:
    http://help.adobe.com/en_US/Acrobat.com/Acrobat/WS396AAA88-4AA4-4a40-87B8-004A5DC1E131.htm l
    Kind Regards,
    Michelle

  • Clone Production Database and Convert into Read Write Mode

    Hi,
    Please help me for below question...
    How to Create Test Database from Production Database without transporting backup of Production Database to Test Database and the Test Database should be in different directory structure and converting into read write mode?
    Please find me a solution as early as possible...
    Thanks & Regards
    Akhil

    if you don't need to move backup from prod to dev you need to create rman catalog and have access on it from dev server , after that you will be able to duplicate your prod to dev without moving backup and database will be in Read write by default .

  • Java.io.Reader - java.io.InputStream

    Hi!
    Is there a way to wrap a java.io.Reader into an java.io.InputStream (like java.io.InputStreamReader does but in the other direction)?
    I found now class doing this job (deduced from java.io.InputStream, taking an java.io.Reader as Constructor Parameter) :-/
    If I want to write my own wrapper I've got two problems:
    * If I want to read data I have to split the char which I read from the wrapped java.io.Reader into a high and a low byte and than return two values.
    * But if I want to read text I can't just split the char into two bytes but I have to convert it
    How can I solve this problem?

    Is there a way to wrap a java.io.Reader into an java.io.InputStream (like java.io.InputStreamReader does but in the other direction)?Why don't you explain what the real problem is? I suspect that there's a solution, but you need to state it. What was the creator and source of the information (file?) that you're trying to read that contains "data" and, apparently, Java characters in a different charset?

  • Convert Raw Binary String to InputStream

    Hi i want to upload a {color:#003366}JPG image file{color} in a {color:#003366}BLOB{color} field in database. At first i was using {color:#003366}AJA{color}X to send file {color:#003366}path{color} to the {color:#003366}servlet{color} creating a {color:#003366}file Object{color} from it, then {color:#003366}FileInputStream{color} from it, and finally passing it to {color:#003366}preparedstatement.setBinaryStream({color}) method. It worked great. But since{color:#003366} Firefox 3{color} stopped sending full path to database i have to use another method.
    So instead of sending image path i used {color:#ff0000}nsIDOMFile{color} property of Firefox 3. It has a method {color:#003366}getAsBinary(){color} which Returns a DOMString containing the file's data in {color:#003366}raw binary{color} format. Now i access this {color:#003366}string{color} from servlet using{color:#003366} request.getParameter(){color} method which creates a {color:#003366}String containing bit code of the image file{color} (I suppose). Now how to convert this string to {color:#003366}InputStream{color} so that i can store this in BLOB field in database using prepared statement.
    Right now I am using following code but it doesn't seem to work.
    String image=request.getParameter("image");
        try{
          InitialContext context = new InitialContext();
          dsource = (DataSource)context.lookup("java:comp/env/jdbc/DataSource");
          con = dsource.getConnection();
          ps = con.prepareStatement("SOME STATEMENT");
          ByteArrayInputStream imagestream = new ByteArrayInputStream(image.getBytes());
          ps.setBinaryStream(1, imagestream, imagestream.available());
          int i = ps.executeUpdate();Edited by: Wonder01 on Oct 22, 2008 12:24 PM

    Yeah i came across that too. But these show either iframes hack method (which really isn't ajax) or else writing large pieces of code just to generate the binary stream of the file, then manually creating multipart/form-data request were the only options until Firefox 3 introduced nsIDOMFile. See this and read first few lines (you'll understand what i mean). So i send request in the form of a parameter containing Raw Binary format of the file
    Now going over to the servlet side i need to somehow accept this parameter and insert in database. First i need to know how should i receive this on servlet (By using request.getParameter() or some other method). And secondly, how to convert that to either a byte array or InputStream. I searched for it and think this might be useful. This page shows 1.) how to convert an array of raw binary data into an array of ASCII 0 and 1 characters and 2.) how to convert a String to byte array where each char of the String represents an ASCII '0' or '1'. But what i nedd is slightly different, I need to convert a String containing Raw Binary into byte array.
    And thanks for the information on the file paths. It was really helpful

  • How to convert data read in byte to decimal number?

    The following are a source code to read from a serial port, but i can't convert the data that i read to decimal number and write it on a text file.....can anyone kindly show me how to solve it? thanks
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class Read implements Runnable, SerialPortEventListener {
         // Attributes for Serial Communication
         static Enumeration portList;
         static CommPortIdentifier portId;
         SerialPort serialPort;
         static OutputStream outputStream;
         InputStream inputStream;
         Thread readThread;
         public static void main(String s[])
         portList=CommPortIdentifier.getPortIdentifiers();
         while(portList.hasMoreElements())
              portId=(CommPortIdentifier)portList.nextElement();
              if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
                   if(portId.getName().equals("COM1"))
                        System.out.println( portId.getName());
                        Read ss=new Read();
              }     // end of while
    }          // end of main
    public Read()     {
    try{
              serialPort=(SerialPort)portId.open("Read", 2000);
    catch(PortInUseException e)     {}
         try{
              inputStream=serialPort.getInputStream();
              System.out.println(inputStream);
    catch(IOException e)     {}
         try{
              serialPort.addEventListener(this);
    catch(Exception e)     {}
              serialPort.notifyOnDataAvailable(true);
         try{
              serialPort.setSerialPortParams(9600,
              SerialPort.DATABITS_8,
              SerialPort.STOPBITS_1,
              SerialPort.PARITY_NONE);
              }catch(UnsupportedCommOperationException e)     {}
              readThread=new Thread(this);
              readThread.start();
         }//end of constructor
         public void run()
              try     {
                   Thread.sleep(200);
              }catch(InterruptedException e)     {}
         public void serialEvent(SerialPortEvent event)
              switch(event.getEventType())
                   case SerialPortEvent.BI:
                   case SerialPortEvent.OE:
                   case SerialPortEvent.FE:
                   case SerialPortEvent.PE:
                   case SerialPortEvent.CD:
                   case SerialPortEvent.CTS:
                   case SerialPortEvent.DSR:
                   case SerialPortEvent.RI:
                   case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                   break;
                   case SerialPortEvent.DATA_AVAILABLE:
                   byte[]readBuffer=new byte[8];
                   try{
                        while(inputStream.available()>0)
                             int numBytes=inputStream.read(readBuffer);
                             //System.out.println("hello");
                        System.out.print(new String(readBuffer));
                        }catch(IOException e)     {}
                   break;
                   }     // end of switch
                   try     {
                        inputStream.close();
                        }catch(Exception e5)     {}
         }          // end of serialEvent

    Is it a float or a double?
    For a float, the decimal should be 4 bytes (small numbers like 1.1 start with the byte 0x40). Convert these 4 bytes to an int, using byte-shifting would probably be easiest.
    int value = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0);//b# are bytesNow to convert it to a float, use
    Float.intBitsToFloat(value);Now if you want double percision, You will have 8 bytes instead of 4, and need to be converted to a long instead of an int through byte-shifting. Then use Double.longBitsToDouble(long bits) to get the double

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • How do I convert a StringReader to an InputStream?

    Hi:
    I have a String, and I need an InputStream - how do I create a stream from a string? My first idea (which may be wrong) is to create a StringReader.
    Thanks, Erik

    InputStream is = new ByteArrayInputStream("your string".getBytes("your desired character encoding"));The big question is - what character encoding do you desire? You can get the platform default encoding by using -
    InputStream is = new ByteArrayInputStream("your string".getBytes());but this frequently is not what is required. If you don't really care then you can cover just about everything with "utf-8".
    P.S. Your thread title and your thread content do not really match!

  • Error converting a read string to type Double.

    I'm trying to read data stored in a text file, a mixture of strings and data.
    Using MyReader As New FileIO.TextFieldParser(source)
    Do
    intSampleCnt = intSampleCnt + 1
    strSample(intSampleCnt) = MyReader.ReadLine ' Reads a string like "filename.txt"
    dblOggLength(intSampleCnt) = CDbl(Val(MyReader.ReadLine)) ' <= Crash occurs here. Reads a number like 9.87654321
    ' additional code...
    Loop Until intSampleCnt = 10
    End Using
    Big problem: *I'm* not getting the error so I can't reproduce it. OTHER users are telling me they are getting the following error:
    System.InvalidCastException: Bringing the line "0.Au" to type "Double" is invalid. ---> System.FormatException: Input string had invalid
    format.
    No idea where "0.Au" is coming from. It's not in my file. Originally, I simply read the line and assigned it to the dblVariable (which worked for me). When users started reporting the error, I tried using:
    dblVar = CDbl(MyReader.ReadLine)
    When that failed, I tried:
    dblVar = CDbl(Val(MyReader.ReadLine))
    I must be on the wrong track. No idea why others are getting errors but not me. Any ideas? Thx.

    The first suggestion will set things up for you but you need to play with this
    Another suggestion is to place the culture code as the first line in the file i.e. to get the current culture code then change how data is written to the file
    System.Globalization.CultureInfo.CurrentCulture.Name
    Then read the file i.e
    Source text file
    fr-BE
    Somename 1 1000,56
    AnotherName 9,99
    Code
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim FileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "France.txt")
    Dim style As NumberStyles = NumberStyles.Number Or NumberStyles.AllowDecimalPoint
    Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(IO.File.ReadAllLines(FileName)(0))
    Dim number As Decimal
    Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName)
    MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {vbTab}
    Dim currentRow As String()
    While Not MyReader.EndOfData
    Try
    currentRow = MyReader.ReadFields()
    If Not currentRow.Length = 1 Then
    If Decimal.TryParse(currentRow(1), style, culture, number) Then
    Console.WriteLine("Converted '{0}' to {1}", currentRow(1), number)
    Else
    Console.WriteLine("Unable to convert '{0}'", currentRow(1))
    End If
    End If
    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
    ' You decide how to handle issues
    End Try
    End While
    End Using
    End Sub
    Results
    Converted '1000,56' to 1000.56
    Converted '9,99' to 9.99
    Detect Decimal separator
    System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • About abstract method read() in class InputStream (third message)

    The subclass FilterInputStream is not abstract and extend InputStream: have you ever seen the implementation of that method in the source code available in SDK? It only calls that abstract method!!! I think it is not a very simple problem and anyway the answer is not in my diffrent books. Thanks for your non trivial answer.

    Please post this as a "reply" in your original thread
    http://forum.java.sun.com/thread.jspa?threadID=5192979&tstart=0
    Don't start a new thread, simply reply to one of the other posts in the original thread (there is a button "reply" on the right hand side).

  • About abstract method read() in class InputStream

    I would like to know if behind the method
    public abstract int read() throws IOException
    in the abstract class InputStream there is some code that
    is called when I have to read a stream. In this case where can I find
    something about this code and, if is written in other languages, why
    is not present the key word native?
    Thanks for yours answers and sorry for my bad english.

    Ciao Matteo.
    Scusa se ti rispondo in ritardo... ma ero in pausa pranzo.
    Chiedimi pure qualcosa di pi? specifico e se posso darti una mano ti rispondo.
    Le classi astratte sono utilizzate per fornire un comportamento standard lasciando per? uno o pi? metodi non implementati... liberi per le necessit? implementative degli utilizzatori.
    Nel caso specifico la classe InputStream ? una classe astratta che lascia non implementato il metodo read(). Tu nel tuo codice non utilizzerai mai questa classe come oggetto, ma nel caso specifico una sua sottoclasse che ha implementato il metodo read().
    Se vai nelle api di InputStream vedrai che ci sono diverse sottoclassi che estendono InputStream. Guarda ad esempio il codice di ByteArrayInputStream: in questa classe il metodo read() non ? nativo ma restituisce un byte appartenente al suo array interno.
    I metodi nativi (ad esempio il metodo read() della classe FileInputStream) non hanno implementazione java ma fanno invece riferimento a delle chiamate dirette al sistema operativo.
    Per quanto riguarda la classe FilterInputStream di cui parlavi: essa nel suo costruttore riceve un InputStream. Questo significa che si deve passare nel costruttore non la classe InputStream (che ? astratta) ma una classe che la estende e che quindi non sia astratta. Il motivo per il quale FilterInputStream faccia riferimento a una classe di tipo InputStream al suo interno, ? che in java gli stream di input e di output possono essere composti l'uno sopra l'altro per formare una "catena" (a tal proposito vedi per maggiori dettagli uno dei tani articoli che si trovano in rete.... ad esempio ti indico questo http://java.sun.com/developer/technicalArticles/Streams/ProgIOStreams/). Comunque per dirla in due parole: tu puoi voler usare un FileInputStream per leggere un file, ma se hai bisogno di effettuare una lettura pi? efficiente (quindi bufferizzata) puoi aggiungere in catena al FileInputStream un oggetto di tipo FilterInputStream (nel caso specifico un BufferedInputStream che non ? altro che una sottoclasse di FilterInputStream).
    Spero di aver chiarito qualche tuo dubbio!
    Ciao
    Diego

  • Converting types/reading using java.io.file

    I have an existing method that reads a directory.
    File[] list = dir.listFiles();
    I populate a vector from this file list.
    vector.add(list);
    What I am currently trying to do is populate this vector from another source which happens to be another vector. I am basically replacing reading from a directory to reading from a vector that already has the file list. The problem I am having is that the value that I am populating the receiving vector with, the type needs to be "file".
    The vector that I am reading from contains string values of the filepath+filename
    Thanks.

    So, disregarding all that stuff about Vectors, your question is how to convert a String (of a certain form) to a File object? To answer that you could look in the API documentation for File and check out the available constructors. It appears that you have a pathname already, so the second constructor in the list, "new File(pathname)" is what you want.

  • Best way to read chars from InputStream

    Hope this is not a too newbie question.
    Suppose I have an unbuffered InputStream inputStream, what is the best way to read chars from it (in terms of performance)?
    Reader reader = new BufferedReader(new InputStreamReader(inputStream));
    reader.read()
    or
    Read reader = new InputStreamReader(new BufferedInputStream(inputStream))
    reader.read()
    Is there a difference between the two and if so, which one is better?
    thanks.

    If you are reading using a buffer of your own, then adding a buffer for binary data is a bad idea.
    However for text, using a BufferedInputStream could be better as it reduces calls to the OS.
    If it really matters, I suggest you do a simple performance test which runs for at least a few seconds to see what the difference is. (You should runt he test mroe than once)
    Edited by: Peter__Lawrey on 20-Feb-2009 21:37

Maybe you are looking for

  • Imprimir Número de série do item na Nota Fiscal -  usando o PLD

    Boa Tarde. Estou desenvolvendo um layout de Nota fiscal para itens que possuem garantia, então é necessário que seja impresso, juntamente com a descrição do Item o número de série. Já tentei imprimir o número colocando um field com OSRI:IntrSerial, m

  • Problem in  Installation of oracle 11i

    Hi, I'm trying to install oracle 11i apps in windows server. I have done all prerequsite steps before starting intallation. In front end screen its saying compled unziping 81 of 114 at (71%) at one particular point the installation is not proceeding

  • External speaker stopped working

    My external speaker on my i-phone 4s stopped working suddenly.  I was told to hold both the round button & the start up button together to reset.  This seemed to work for a half a second, then it cut right back out again.

  • Printing emails with multiple recipients

    I need to be able to submit an order to my suppliers and simultaneously send the same list to my office, but I got an email that stated the following: The email was sent to multiple printers or recipients. (HP's ePrint service only processes emails s

  • Schema Validation Key/Keyref and substitutionGroup Problem

    First, thank you for fixing the schemaLocation problem. My next question is about key/keyref and substitution. If I define a key/keyref relationship inside one element, then use another element to substitute that element, I found that the key/keyref