However I can't suggest any better way to do it (i.e. something which would at least compile) because I'm not clear on what it means to "convert" an output stream to an input stream. Could you explain that a bit?
Well, it depends on requirement. Here is my business case..
I am working with Apache FOP where JAXB annoted java beans are used to generate PDF documents. Here are two steps.
1) JAXB marchaller converts bean to XML output stream. I dont want to write to a file.
2) Above output stream needs to go in as inout to FOP transformer. So I need to convert above output stream to input stream.
Above code is working fine for me. Just wanted to know is there any better way to that.
So you're saying you need to write everything to the OutputStream first, and only then use the InputStream? Why? This requires a buffer to store everything that's written - something your current ByteArrayOutputStream will do for you. If there's a lot of data, this buffer will become very large.
If you use PipedInputStream and PipedOutputStream there is one thing you need to be very aware of - both streams need to be open until the other is done. If you close the PipedOutputStream (for example by letting its thread end), reading from the PipedInputStream will cause exceptions. That's mentioned in the Javadoc of PipedInputStream and PipedOutputStream:
A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.
The pipe is said to be broken if a thread that was reading data bytes from the connected piped input stream is no longer alive.
Me too i had this kind of problem: a library want to write its data to an OutputStream and later another library wanted to read the same data from an InputStream.
There are 3 possible approaches:
* the one you were doing: write the data to a ByteArrayOutputStream and read it back from a ByteArrayInputStream. The advantages are: it's easy to implement, and fast if the data fit into memory. Depending on the size of the data it may stress your server or send it OutOfMemory.
* Save the data to a temporary file, and read it back. It's slow, you must be careful in closing the streams.
* use pipes. Pipes are a good compromise between speed and memory usage. They are difficult to implement (you have to instantiate a new Thread in order to use them).
A code sample on how to use pipes:
I wrote a tutorial where I explain tese concepts in a longer way, with code samples.
The sample code above is over simplified, if the intenral function launches an exception it is completely lost, and the outer stream is truncated. To deal with these problems i also wrote an Open Source library (Easystream) to ease the task of using pipes. Have a look if you're still interested.
The only thing that kept the leeches off of me was this tiny ad: