分类: Java
2010-10-12 14:58:07
If you have ever programmed using Java IO, you will quickly run into a situation in which a class creates data on an OutputStream and you need to send it to another class that expects to read the data from an input stream. You'll soon be asking the question, "How do I convert an OutputStream to an InputStream?"
Nowhere in Java will you find a OutpStreamToInputStreamConverter class. Luckily, there are several ways to go about this.
The easiest method is to buffer the data using a byte array. The code will look something like this:
ByteArrayOutputStream out = new ByteArrayOutputStream(); class1.putDataOnOutputStream(out); class2.processDataFromInputStream( new ByteArrayInputStream(out.toByteArray()) );
That's it! The OutputStream has been converted to an InputStream.
The problem with the first method is that you must actually have enough memory to buffer the entire amount of data. You could buffer larger amounts of data by using the filesystem rather than memory, but either way there is a hard limit to the size of the data that can be handled. The solution is create a thread to produce the data to the PipedOutputStream. The current thread can then read the data as it comes in.
PipedInputStream in = new PipedInputStream(); PipedOUtputStream out = new PipedOutputStream(in); new Thread( new Runnable(){ public void run(){ class1.putDataOnOutputStream(out); } } ).start(); class2.processDataFromInputStream(in);
CircularByteBuffer cbb = new CircularByteBuffer(); new Thread( new Runnable(){ public void run(){ class1.putDataOnOutputStream(cbb.getOutputStream()); } } ).start(); class2.processDataFromInputStream(cbb.getInputStream());
// buffer all data in a circular buffer of infinite size CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); class1.putDataOnOutputStream(cbb.getOutputStream()); class2.processDataFromInputStream(cbb.getInputStream());