Reader and InputStream

I notice it is fairly easy to create a reader for an input stream.
   Reader reader = new InputStreamReader( in );However, I don't see any easy way to create an input stream from a reader.
   InputStream in = new ReaderInputStream( reader );Is there an obvious reason for this that I am missing? A reason why someone would never what to do this? Or is there an adapter class that I am just missing?
As always, thanks in advance,
R.

Well, no not really. That's a very specific example (i.e. strings). Basically, I can read content from a variety of places -- the content could come as a ByteArrayInputStream, StringInputStream, FileInputStream and so on -- I won't know which. I use a reader to work with that input stream (possibly filtering it). Then I want to take this content and put it into a database as an InputStream. I can't just use the original input stream because it may have been filtered using a reader. I want to keep these as streams because, in the case that it is a FileInputStream, I don't want to have to load the entire stream into memory as a byte-array. Furthermore, the source content could be binary or text. I want to have two wrapper methods, one that took a Reader and one that took an InputStream. These would them write that data to the database, which is why I was wondering if there was an easy way to wrap a Reader with an InputStream (I already know the reverse is easy). Sounds like I need to introduce another layer of abstraction. Maybe a Content class tree that can get/set an InputStream.

Similar Messages

  • Confusion about Reader() and InputStream()

    I am reading the "Overview of I/O Streams" tutorial, and I'm trying to get a handle on streams. I can't seem to understand whether InputStream() is a subclass of Reader() or if they are just two separate classes. I think they are two separate classe because one reads bytes the other reads chars...but then at the beginning of the tutorial it says everything is derived from the Reader() class. What's the dealio?

    I think you are confused.
    InputStream is not a subclass of Reader. Both of them extend from Object.
    Reader is used to handle the data in the form of characters, while InputStream is used to handle the data in the form of bytes.
    Read the explanation carefully in the tutorial.

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • How to read and write a file in unicode?

    Hello!
    I have a problem with reading and writing files which are saved in unicode. with my current code I get strange boxes in my text
    Do you need a special Reader/Writer for this?
    Please, help me if you have any ideas.
    cheers
    import java.io.*;
    import java.util.*;
    public class StreamConverter {
       static void writeOutput(String str) {
           try {
               FileOutputStream fos = new FileOutputStream("test_uni.txt");
               Writer out = new OutputStreamWriter(fos, "UTF8");
               out.write(str);
               out.close();
           } catch (IOException e) {
               e.printStackTrace();
       static String readInput() {
          StringBuffer buffer = new StringBuffer();
          try {
              FileInputStream fis = new FileInputStream("file_uni.txt");
              InputStreamReader isr = new InputStreamReader(fis, "UTF8");
              Reader in = new BufferedReader(isr);
              int ch;
              while ((ch = in.read()) > -1) {
                 buffer.append((char)ch);
              in.close();
              return buffer.toString();
          } catch (IOException e) {
              e.printStackTrace();
              return null;
       public static void main(String[] args) {
            String inputString = readInput();
            writeOutput(inputString);     
    }

    Are you saying there's only the three boxes at the beginning, and the rest of the text is okay? That sounds like a Byte Order Mark (BOM). The BOM is optional for UTF-8, but Java's I/O classes act like it's forbidden. They should check for it when reading so they can skip over it, but (for now, at least) we have to do that ourselves.
    All you have to do is read the first three bytes from the InputStream and compare them to the BOM. If they match, you start reading the text from that position; otherwise you reset the InputStream and start reading from the beginning.
    http://en.wikipedia.org/wiki/Byte_Order_Mark

  • How to read and parse a remote XML file with Java

    Hi.
    Using J2SE v1.4.2, I'd like to read and parse a remote file:
    http://foo.com/file.xml
    Is it possible with Java? I'd be extremely grateful if someone could provide me any webpage showing a very simple code.
    Thank you very much.

    How about the following?
         import java.io.InputStream;
         import java.net.URL;
         import javax.xml.parsers.DocumentBuilder;
         import javax.xml.parsers.DocumentBuilderFactory;
         import org.w3c.dom.Document;
         public static void main(String[] args) throws Exception {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              URL url = new URL("http://foo.com/file.xml");
              InputStream inputStream = url.openStream();
              Document document = db.parse(inputStream);
              inputStream.close();
         }-Blaise

  • How to use Reader or InputStream to get byte[]

    Any opinions on the best way to get a byte[] using java.io.Reader or java.io.InputStream?
    I haven't used these in anger before, so sorry for the rookie nature!
    Any simple examples would be much appreciated!
    Thanks

    So sorry, I wasn't really listening . . . YOU WANT BYTE[]! OH! <8*O
    From DataInputStream docs v1.3.1:
    read
    public final int read(byte[] b)
                   throws IOException
        Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.
        If b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
        The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.
        If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed.
        The read(b) method has the same effect as:
    read(b, 0, b.length)
    Overrides:
    read in class FilterInputStream
    Parameters:
    b - the buffer into which the data is read. Returns:
    the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. Throws:
    IOException - if an I/O error occurs.See Also:
    FilterInputStream.in, InputStream.read(byte[], int, int)

  • Java concurrency and inputstream

    HI,
    I want to write the image file from a database to disk by using a queue. I can write these images on disk from the result set.
    Can someone tell me where I am wrong in the following code? I get: "trying to write to disk: Closed Connection"
    Thank you.
    {code}
    public class ExtractPicture implements Runnable{
        private BlockingQueue<InputStreamMessage> queue;
        public ExtractPicture(BlockingQueue<InputStreamMessage> queue){
            this.queue = queue;
        @Override
        public void run() {
            try(Connection conn = new DatabaseConnection().getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select mypicture from testpicture")){           
                while(rs.next()){
    //                System.out.println(rs.getInt("mypicture") + " <== added");
    //                queue.put(rs.getInt("id"));
                    InputStreamMessage ism = new InputStreamMessage(rs.getBinaryStream("mypicture"));
                    try{
                        queue.put(ism);
                    }catch(Exception e){
                        System.out.println(e.getMessage());
            }catch(Exception e){
                System.out.println(e.getMessage());
    class Consumer implements Runnable{
        private BlockingQueue<InputStreamMessage> queue;
        public Consumer(BlockingQueue<InputStreamMessage> queue){
            this.queue = queue;
        @Override
        public void run() {
            try{           
                int z = 0;
                InputStreamMessage is;
    //            (is = queue.take()) != null
                while((is = queue.take()) != null){
                    System.out.println("consumer aa" + is.getInputStream());
    //                writeToDisk(is.getInputStream(), "c:\\temp\\p" + z + ".jpeg");
                    try{
                        int c = 0;
                        OutputStream f = new FileOutputStream(new File("c:\\temp\\p" + z + ".jpeg"));
                        while((c = is.getInputStream().read()) > -1 ){
                            f.write(c);
                        f.close();
                    }catch(Exception exce){
                        System.out.println("trying to write to disk: " + exce.getMessage());
                    z++;
            }catch(Exception e){
                System.out.println(e.getMessage());
    class InputStreamMessage{
        private InputStream is;
        public InputStreamMessage(InputStream is){
            this.is = is;
        public InputStream getInputStream(){
            return is;
    class RunService{
         public static void main(String[] args) {
            BlockingQueue<InputStreamMessage> queue = new ArrayBlockingQueue(10);
            ExtractPicture ep = new ExtractPicture(queue);
            Consumer c = new Consumer(queue);
            new Thread(ep).start();
            new Thread(c).start();
    {code}

    This is really a JDBC issue: Java Database Connectivity (JDBC)
    Your code is getting a 'STREAM' from the result set and putting a reference to that stream in a queue.
    But then the code executes 'rs.next()' which closes the stream and attempts to move to the next row, if any, of the result set.
    Stream data MUST BE read immediately. Any attempt to access columns after the column being streamed or moving to another rows will close the streamj.
    See the JDBC Dev Guide for the details of processing LOBs and using streams.
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/jstreams.htm#i1014109
    Data Streaming and Multiple Columns
    If a query fetches multiple columns and one of the columns contains a data stream, then the contents of the columns following the stream column are not available until the stream has been read, and the stream column is no longer available once any following column is read. Any attempt to read a column beyond a streaming column closes the streaming column.
    Also see the precautions about using streams:
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/jstreams.htm#i1021779
      Use the stream data after you access it. 
    To recover the data from a column containing a data stream, it is not enough to fetch the column. You must immediately process the contents of the column. Otherwise, the contents will be discarded when you fetch the next column.
    It is important that the process consuming the stream has COMPLETE control over the components needed to process it properly. That includes the connection, statement and result set.
    As TPD pointed out by defining the connection, statement and result set within a method those instances goe OUT OF SCOPE when the method ends.
    Since you also defined the objects within a try block they go out of scope when the block exits even if the method doesn't end.
    You didn't say why you are trying to use queues to do this but I assume it is part of some multi-threaded application. If so you have some additional architectural considerations in terms of keeping things modular while still being able to share certain components.
    For example how are you connections being handled? Are you using a connection pool? That 'queue' processsor need sole access to the connection being used to stream an object. Your code ONLY puts a reference to a stream on the queue but then has to WAIT until the stream has been FULLY READ before that code can try to read the next column, next row or close the result set.
    That makes those two processes mutually dependent and you aren't taking that dependency into account.
    Hopefully you are doing the dev and testing using TINY files until things are working properly?.

  • How to read and then extract HTMl source code using java program?

    Hi,
    Could someone tell me how to read and then extract the content of certain tag from html source code. For example, given url http://.... , I would like to know what the <Title> content <Title> in that page is.
    Any help is greatly appreciate.

    Use a URLConnection to make the connection to the page at the needed URL. From the URLConnection, you can get an InputStream that is the stream of data from that page. Just search through the stream and find the <title> tags (don't forget to check for case sensitivity).

  • How to read and write on sockets?

    Hi.
    I want to read and write data from sockets, Can anybody help me.
    Regards.
    Bilal Ghazi.

    You need 3 classes. Receiver, RemoteThread and Sender. These classes are not tested by me
    //these classes are on the clientside
    public class Receiver{//listens to connections
    ServerSocket serverSocket = new ServerSocket(port);
    while (...){
    Socket client=serverSocket.accept();//waits for new connection
    RemoteThread thread=new RemoteThread(client);
    thread.start();
    serverSocket.close();
    public class RemoteThread{
    final static int BUSYWAITTIME=10;//10 ms
    Socket socket;
    public RemoteThread(Socket _socket) {
    this.socket = _socket;
    public void run() {
    BufferedOutputStream out = new java.io.BufferedOutputStream(socket.getOutputStream(),socket.getSendBufferSize());
    int inBuffSize=socket.getReceiveBufferSize();
    BufferedInputStream in = new java.io.BufferedInputStream(socket.getInputStream(),inBuffSize);//wait until get enuff
    byte[] buff=new byte[inBuffSize];
    while (...) {
    //read
    while(in.available()<=0 && !stopped){//just wait for it to become ready
    try{wait(BUSYWAITTIME);}catch(InterruptedException e){}
    int readBytes=in.read(buff);
    //do something with the bytes in buff
    //This class is on the clientside
    public class Sender{
    Socket socket = new Socket(host, port);//connects to server
    OutputStream out = socket.getOutputStream();
    PrintWriter outPrinter=new PrintWriter(out,true);
    InputStream in = socket.getInputStream();
    //use out or outPrinter to write to server
    Gil

  • OutputStream and InputStream issues

    Hi
    I have an echo server and a client.
    Now the problem is that whenever I send something to the server it comes up gibberish, even though I transform it to String.
    Server code:
    public class Server
      StringTokenizer st;
      BufferedOutputStream out;
      InputStream in;
      private void init()
        try
          {srv = new ServerSocket(port);}
        catch(IOException e)
          {System.err.println("Could not listen on port " + port + ".\nLet's trace:\n" + e + "\n"); System.exit(-1);}
      private void reset()
        try
          {socket = srv.accept();}
        catch(IOException e)
          {System.out.println("Could not open socket for client, let's trace:\n" + e + "\nExiting now...");}
        try
          out = new BufferedOutputStream(socket.getOutputStream());
          in = socket.getInputStream();
        catch(IOException e)
          System.out.println("Could not open IO, exiting now...");
      private byte[] receive() throws IOException
        byte[] inputBuffer = new byte[100];
        byte[] byteInput = new byte[in.read(inputBuffer)];
        for(int i = 0; i < byteInput.length; i++) byteInput[0] = inputBuffer;
    return byteInput;
    public Server() throws IOException
    init();
    String input = "";
    byte[] byteInput = null;
    int params;
    String stage = "";
    while (input != null)
    reset();
    try
    byteInput = receive();
    input = new String(byteInput);
    // Parsing data //
    st = new StringTokenizer(input, " ");
    params = st.countTokens();
    stage = st.nextToken();
    System.out.println("client: " + input + "\nparams=" + params + "\nstage=" + stage);
    The client is using an OutputStream to send out bytes and InputStream to recieve bytes. I need to leave it on the bytes level so I cannot use any subclasses of OutputStream or InputStream.
    Any idea why I get junk on the server side?
    Thanks

    Thanks for the feedback, much appreciated!
    I don't see why not. Please explain further. If
    you're sending Strings you should be reading Strings,
    probably with DataInputStream.readUTF()/writeUTF(),
    and you wouldn't be having any of the problems above.
    If you're not sending Strings don't convert the data
    from/to Strings at all, just process the bytes
    directly.Because I only need to convert to String at this initial stage.
    After this the client will send bytes and server will process bytes.
    In general I need to measure the Throughput of a TCP link, so the client has to send probes of various size (in particular 1 byte, 100 bytes, 400 bytes...). But before this can happen, the client needs to prepare the server for what's coming by sending a String with a special format. However, since a character is encoded into 2 bytes, I don't see how to make this work rather then do this nasty half byte half character processing.
    byte[] inputBuffer = new byte[100];
    byte[] byteInput = new byte[in.read(inputBuffer)];
    That could result in trying to allocate new byte[-1], which won't work. It could >also result in any size of byteInput from 1 to 100. There is no guarantee you >have read the whole request at this point.Yes I was aware of the fact that read() can return -1. I ignored it at this point because I was stuck with the junk problem. If it returns -1 an exception will be thrown so I am less worried about this for the moment.
    I took a 100 because the max size of any message send by the client is not going to exceed this. Restricted by the protocol I work around.
    for(int i = 0; i < byteInput.length; i++)
    byteInput[0] = inputBuffer;
    Waste of time. See above.Ok, I agree I am not the most sophisticated programmer :) but how else would I parse meaningful data out of that 100 byte buffer?
    while (input != null)
    How is input ever going to be null?Sorry I should have said while(0) or something of that nature.
    It's an endless loop. Originally the server worked differently so that statement actually made sense, but now it's just an endless loop.
    However I still don't understand why I get junk.
    If I send only one character from the client the server gets it correctly.
    It's only a problem once I send some stuff.
    Any suggestions?
    Many Thanks!
    Message was edited by:
    eXKoR
    Message was edited by:
    eXKoR

  • Due to my laptop screen failing i have to return to facory settings, can i reinstall adobe reader and adobe air afterwards?

    Due to my laptop screen failing I have to return it to factory settings, can I reinstall adobe reader and air afterwards?

    I don't see why not. Do you foresee a special difficulty?

  • In iCal and Notifications on a notebook, is it possible to expand the notes window to make it easier to read and write notes?

    In iCal and Notifications on a notebook, is it possible to expand the notes window to make it easier to read and write notes? In the past, I have used Outlook calendar and tasks and I was able to expand the windows which allowed me to put a great amount of details into either the notes section in events and tasks. It would be great to be able to do this in iCal and Notifications as well. I am using a Macbook Pro with OS X 10.8. Thank you very much for assistance with this.

    HI,
    Try Spaces for a virtual desktop.
    http://www.ehow.com/how2189851use-spaces-mac-os-x.html
    Carolyn

  • Reader and Windows 8.1 FULL SCREEN?

    Is there a way to view a document in Reader and Windows 8.1 other than on FULL SCREEN.  In previous versions, I could look at a.pdf file while working on another file on my computer screen.  This allowed me to get info from the .pdf file and input into the other program.

    It might  be that you're viewing with an app written to Microsoft's new and exciting "modern" interface which is always full screen. Apparently it's much better and more exciting.
    Microsoft Reader comes with Windows 8 and runs that way. Adobe also offer "Adobe Reader Touch" which runs that way.
    Some of us old dinosaurs who think it might be neat to arrange multiple apps so we can do more than one thing at once like to run the "legacy" apps like Adobe Reader.

  • I have an external hard drive, from Iomega. However, I cannot copy or save any file to it. On my PC it says that is possible to read and write in it, but in my Mac, it says I can only read. can somebody help me?

    I have an external hard drive, from Iomega. that I can open and see my files. However, I cannot copy or save any file to it. On my PC I have it says that is possible to read and write in it, but in my Mac, it says I can only read. can somebody help me?
    Also, Im a photographer, so I like to name a lot of files at the same time (used to do in on PC and it was very usefull.) cannot find out how to do it on my Mac. Really appretiate if some one can give me a solution! Thanx

    Your drive is formatted with the NTFS file system.  OS X can read but not write to the NTFS file system.  There are third party drivers available that claim to add the ability to OS X to write to an NTFS partition.  I have not tried them and don't know if they work.
    The only file system that OS X and Windows can both write to natively is the FAT32 file system.

  • Problems with Adobe Reader and Flash Player

    I had an Adobe update last Monday and, ever since then, I can't view documents (eg credit card statements) on screen and sites that I previously visited regularly without problem suddenly say that I need to have Adobe Flash Player installed. I've downloaded Adobe Flash Player and it says it's installed correctly but when I return to the site, it still says I need Adobe Flash Player. I've also tried doing an uninstall first and then an instal but the same thing happens. I've run disk first aid and it found a problem with the Head which it fixed but I still can't open documents using Adobe in Safari. Adobe Plug ins tells me that the Internet Access plug in is not loaded but when I ran 'repair Adobe Reader installation", it said there were no missing components detected and repair was not needed. I don't know if it's relevant but I've been having problems with Safari for several weeks, quitting 3 or 4 times a day, mainly when I'm switching from Safari to another programme such as Entourage or Excel.
    Message was edited by: Aileen2

    Hi Carolyn
    I don't think I made it clear on the original post that I'm having problems with both Adobe Reader AND Adobe Flash Player. Unfortunately, all the Adobe Reader sites are confidential so I can't give you an illustration on that but for the Adobe Flash Player, try www.jacquielawson.com/ - you can preview cards without being signed in. With the Adobe Reader problems, I get a picture of a blank 'piece of paper' with a small blue square in the top right hand corner that has a white question mark inside it. The first time this happened to me, I was on the UK Inland Revenue site trying to print out some end of year forms. I phoned the Revenue's helpline and they said to try doing a 'save as' to my desktop. It seemed bizarre - saving a blank piece of paper - but lo and behold, when I opened it on my desktop, the forms appeared exactly as normal. However, I've since tried this 'save as' technique with my credit card statement and I still get a blank piece of paper with a blue square and white question mark when I open the desktop copy.
    Thanks for your help and patience. I really appreciate it.
    Aileen

Maybe you are looking for

  • PO Provision Report

    Hi, Please provide the query for PO Provision Report(Purchasing). Please help. Regards Suresh

  • How do I assign "you are here" on these accordion buttons?

    With the help of Kin(one of the forums members) I have been able to assigned individual buttons to open specific spry accordion panels and display it's contents. Here's the page, the buttons I'm referring to are the numbers 1 to 4 http://www.patrickj

  • CC suddenly thinks I am using trial versions

    CC suddenly thinks I am using trial versions of all my apps. App manager launches asking to continue trial.

  • Bit Rate settings for compressing to iPhone

    Hello- I have Compressor 3.05 and I'd like to use a bit-rate setting that is not available in the Apple-provided iPhone presets. I'm looking for something around 150. Is there a way to create a custom preset for iPhone compatible video? I can't seem

  • ADF 11g TP3 or Production

    Is there any information out there as far as Oracle's delivery dates for ADF 11g Production and/or an ADF Technology Preview 3 version? We are currently in the process of developing a small beta version of our software using TP2, but concern is mount