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?

Similar Messages

  • Create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)

    Ahhh!!!
    Ahem, when I try to compile the file below, "PhoneDirectory.java", I get the following compilation error message:
    PhoneDirectory.java:12: create(java.io.InputStream) in Scanner cannot be applied to (java.io.File)
        Scanner fin = Scanner.create(file);After quite a bit of tweaking... I'm right back where I started. I'm a seasoned programmer, as far as concepts are concerned, but rather new to JAVA.
    The error seems to be occuring where a new instance of "Scanner" is supposed to be created. It uses file I/O, and I had only used the Scanner class for the keyboard input in the past.
    Looking at the Scanner class, everything seems to be right to me. I'm probably missing some simple fundamental concept, and I've been pulling my hair out trying to get it... Please help me shed some light on this situation!
    =========
    PhoneDirectory.java
    =========
    import java.io.*;
    // Read a file of names and phone numbers
    // into an array. Sort them into ascending
    // order using bubble sort.
    // Print names and numbers before and after sort.
    public class PhoneDirectory {
      public static void main (String[] args) {
        PhoneEntry[] directory = new PhoneEntry[200];
        File file = new File("c:\\jessica\\phonenum.txt");
        Scanner fin = Scanner.create(file);
        int numberEntries = 0;
        // read array from file
        while (fin.hasNextInt())
          directory[numberEntries++] = new PhoneEntry(fin);
        // print array as read
        for (int i=0; i<numberEntries; i++)
          System.out.println(directory);
    // sort by ordering defined in PhoneEntry,
    // in this case lastName firstName
    bubbleSort(directory, numberEntries);
    // print sorted array
    System.out.println(
    "============================================");
    for (int i=0; i<numberEntries; i++)
    System.out.println(directory[i]);
    static void bubbleSort(PhoneEntry[] a, int size) {
    // bubbleSortr: simple to write, but very inefficient.
    PhoneEntry x;
    for (int i=1; i<size; i++)
    for (int j=0; j<size-i; j++)
    if (a[j].compareToIgnoreCase(a[j+1]) > 0) {
    // swap
    x = a[j]; a[j] = a[j+1]; a[j+1] = x;
    =========
    PhoneEntry.java
    =========
    class PhoneEntry {
    // number, name entry for a line in a Phone Directory
      protected int area;
      protected int prefix;
      protected int number;
      protected String firstName;
      protected String lastName;
      public String toString() {
      // format name and phone number to printable string
        String x = lastName + ", " + firstName;
        x = x +
        " . . . . . . . . . . . . . . .".substring(x.length())
        + "(" + area + ") " + prefix + "-" + number;
        return x;
      public int compareToIgnoreCase(PhoneEntry v) {
      // alphabetically compare names in this to names in v
      // return negative for this < v, 0 for ==,
      //        positive for this > v
        int m = lastName.compareToIgnoreCase(v.lastName);
        if (m == 0) m = firstName.compareToIgnoreCase(v.firstName);
        return m;
      public PhoneEntry(Scanner fin) {
      // input a PhoneDirectory entry. Must be space delimited
      // area prefix suffix lastname firstname
        // number
        area = fin.nextInt();
        prefix = fin.nextInt();
        number = fin.nextInt();
        // read rest of line
        String name = fin.nextLine();
        // split name into lastName firstName
        int p = name.indexOf(' ');
        if (p > 0) {
            lastName = name.substring(0,p);
            firstName = name.substring(p+1);
        else {
            lastName = name;
            firstName = "";
    }=========
    Scanner.java
    =========
        This class does input from the keyboard.  To use it you
        create a Scanner using
        Scanner stdin = Scanner.create(System.in);
         then you can read doubles, ints, or strings as follows:
        double d; int i; string s;
        d = stdin.nextDouble();
        i = stdin.nextInt();
        s = stdin.nextLine();
        An unexpected input character will cause an exception.
        You cannot type a letter when it's expecting a double,
        nor can you type a decimal point when it's expecting an int.
    import java.io.*;
    public class Scanner {
    // Simplifies input by returning
    // the next value read from the
    // keyboard with each call.
      private String s;
      private int start=0, end = 0, next;
      private BufferedReader stdin;
      Scanner(InputStream stream) {
        start = end = 0;
        // set up for keyboard input
        stdin = new BufferedReader(
        new InputStreamReader(stream));
      public static Scanner create(InputStream stream) {
        return new Scanner(stream);
      double nextDouble() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         double d = Double.parseDouble(s.substring(start,next));
         start = next+1;
         return d;
      public int nextInt() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         next = s.indexOf(' ',start);
         int d = Integer.parseInt(s.substring(start,next));
         start = next+1;
         return d;
      public String nextLine() {
         if (start >= end)
           try {
            s = stdin.readLine().trim() + " ";
              start = 0;
             end = s.length();
          catch (IOException e) {System.exit(1);}
         String t = s.substring(start,s.length()-1);
         start = end = 0;
         return t;
    }=========
    phonenum.txt
    =========
    336 746 6915 Rorie Tim
    336 746 6985 Johnson Gary
    336 781 2668 Hoyt James
    606 393 5355 Krass Mike
    606 393 5525 Rust James
    606 746 3635 Smithson Norman
    606 746 3985 Kennedy Amy
    606 746 4235 Behrends Leonard
    606 746 4395 Rueter Clarence
    606 746 4525 Rorie Lonnie

    I don't see a Scanner.create() method in the Scanner class but I do see a constructor with the signature you want. Change
    Scanner fin = Scanner.create(file);
    to
    Scanner fin = new Scanner(file);

  • 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.

  • Non-blocking read from an InputStream??

    Hello all, I have a bit of a problem. I have a GUI based app that, through the mindterm SSH classes, runs a "tail -f /var/log/somelog" command on a *nix server. The purpose of the app is to make looking through the log's easier for the non-computer lay-person. The problem is that if they click the stop button to stop the output of the tail it doesn't actually stop that thread until the next line is appended to the end of the log file. That could be a second or an hour. So what I need is a way to somehow stop that tail -f command when the user hits stop and not have to wait for the read to occur.
    What I'm working with is a com.mindbright.util.InputStreamPipe that is a subclass of java.io.InputStream. I've tried several things. Such as the seda.nbio.NonblockingInputStream which gives me a runtime classCastException when trying to cast the com.mindbright.util.InputStreamPipe to a seda.nbio.NonblockingInputStream. I've tried creating a java.nio.channels.ReadableByteChannel and using it's read method but that also blocks.
    So my question is, does anyone have any clever solutions to this particular problem? I thought the way to beat it was to find some mechanism to do a read that will just get passed by if there's nothing to read then have it wait an arbitrary amount of time before reading again. So the longest the user would have to wait would be that arbitrary amount of time. But I don't know how to implement this or if it's even a good way to do it.
    Thanks in advance!

    Thanks for the help dubwai. I actually found a way to accomplish this without any non-blocking balony.
    public void run () {
                            try {
                                    java.io.InputStream is = tbs.getConsoleOut();
                                    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
                                    String line = null;
                                    // continue is a volatile boolean that gets set to false when user clicks stop
                                    while ( cont ) {
                                            if ( is.available() > 0 ) {
                                                    line = in.readLine();
                                                    System.out.println("in while: "+line);
                                            } // end
                                            else {
                                                    try {
                                                            java.lang.Thread.sleep(500);
    } // end try
                                                    catch ( java.lang.InterruptedException ie ) {
                                                            System.err.println("Error sleeping: "+ie);
                                                    } // end catch
                                            } // end else
                                    } // end while
                                    is.close(); in.close();
                                    System.out.println("After while");
                                    System.exit(0);
                            } // end try
                            catch ( Exception e ) {
                                    System.err.println("Error reading lines: "+e);
                            } // end catch
                    } // end runThis seems to work on a few trial runs.. Does anyone see any possible random timing issues from this??

  • 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

  • Why is java.io.InputStream.read() so slow???

    Hi everyone,
    I have an applet that reads a file via url. I open the file and read from it using this code:
    URL url = new URL (http://"www.somesite.com/target.txt");
    try {
    InputStream is = url.openStream();
    //reads the raw data from the file
    for(int i = 0; i != -1;) {
    i = is.read();
    //determines dimensions needed for the array
    if(i == '~') {
    dataDimension++;
    rawData += (char) i;
    }catch(IOException ioe) {}
    The code works without errors. (hopefully the above does too, I dont think I introduced any errors when I pasted it over...) The problem is it is unbelieveably slow. When I run it on my file of 85kB in size, the code runs for several minutes on this loop reading in the data in the file. I have no idea why this is...the problem appears to have little or nothing to do with bandwidth as ive tried it on dsl, 56K etc. Ive even writtin a variant that reads the data off my hard drive. No matter where the file resides and how fast of a pipe I give it, it takes just about the same time to complete. My assumption is that either Strings have an increasingly harder time concatenating another string to its end as its size increases or InputStream needs to be layered in another reader object for some strange reason.
    Does anyone have any idea whats happening here? Is there a faster way to get characters from a file into a String?
    I really do appreciate any help I get on this one!
    Thanks in advance for posting.
    Sincerely,
    Nickolas Fellows
    [email protected]

    Haha, Im an idiot...I answered my own question...or at least I think I did.
    Turns out I shoulda been using a StringBuffer and initializing it with a size large enough to hold the file right off the bat. I am assuming making the string recreate its self everytime its size got exceeded was the problem.
    Thx for letting me waste everyones time again :)
    Sincerely,
    Nickolas Fellows
    [email protected]

  • 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

  • Failed to read bytes from InputStream

    Hi,
    I get this excpetion log when I try to read a stream from weblogic. Can anyone help me out why this happens and what
    could be done to overcome this
    ####<Aug 8, 2007 4:48:37 PM EDT> <Error> <HTTP> <sundev01> <fhsserver> <[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1186606117277> <BEA-101019> <[weblogic.servlet.internal.WebAppServletContext@111f9b - name: 'FFMS', context-path: '/FFMS'] Servlet failed with IOException
    java.io.IOException: failed to read '2678' bytes from InputStream; clen: 58512 remaining: 44902 count: 1394
    at weblogic.servlet.internal.ChunkOutput.writeStream(ChunkOutput.java:411)
    at weblogic.servlet.internal.ChunkOutputWrapper.writeStream(ChunkOutputWrapper.java:168)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:496)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:484)
    at weblogic.servlet.FileServlet.sendFile(FileServlet.java:400)
    at weblogic.servlet.FileServlet.doGetHeadPost(FileServlet.java:224)
    at weblogic.servlet.FileServlet.service(FileServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:272)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:165)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3150)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:1973)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1880)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1310)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:179)
    >

    Hi Aravind,
    Which version of weblogic are u using?
    Cheers,
    Lakshmi

  • IOException while reading the the InputStream

    Hi,
    I am running into an issue where I am encounter an IOException while reading the InputStream. The URL sends back XML and is NOT Malformed. What would be causing the IOException?
    URL server = new URL(url);
    HttpURLConnection connection = (HttpURLConnection)server.openConnection();
    connection.setRequestMethod("GET");
    try{
         connection.connect();
         InputStream in= connection.getInputStream();
    }catch(IOException e){
    //Exception while reading the InputStream
    any hints would be greatly appreciated. thanks,
    M

    Here is what I get
    java.io.IOException: Server returned HTTP response code: 505 for URL:
    http://cheese.ddc.dal.earthlink.net/sa/search?upc=0088698190142&mfn="Hewlett-Packard"&producttitle="HP LaserJet 5000 - Printer - B/W - laser - A3 - 1200 dpi x 1200 dpi - up to 16 ppm - capacity: 350 sheets - Parallel, Serial"&partnumber=C4110A&XSL_TEMPLATE=sample.xsl&RESULTS=PARTNERS
    But the URL is Ok. I can see XML being returned in the browser.
    505 The HTTP protocol you are asking for is not supported.
    Now, why would that be?
    Thanks a lot for the help.
    M

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

    I know but my question needs other arguments. When the Java virtual machine must help me in reading some input stream, I imagine it uses some calls to the operating system: I would like to know if behind that method there is something which seems a system call even if is abstract and so without apparently code.

    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).

  • 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.

  • 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

  • Closing Reader without Closing InputStream

    Currently, I have a method :
    void method(InputStream stream) {
        // Create UTF-8 reader by wrapping up the stream.
    }The reason I do not want to have method to accept Reader is that, I want my own method to have own control to decide what type of encoding should be used.
    The problem is, whenever I close the Reader, InputStream will be closed as well. This is not my intention. As InputStream is "opened" by the caller. Hence, the closing operation on InputStream shall be done at caller side.
    Is there any way I can close the Reader in "method", without closing the InputStream passed by caller?
    Thanks.

    The problem is, whenever I close the Reader, InputStream will be closed as well.So don't close it.
    This is not my intention. As InputStream is "opened" by the caller. Hence, the closing operation on InputStream shall be done at caller side.So don't close it.
    Is there any way I can close the Reader in "method", without closing the InputStream passed by caller?Don't close it.

Maybe you are looking for