Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an InputStream of Writer using standard Java library

I have an method which writes data to an OutputStream but needs to return the contents of the OutputStream as an InputStream

public InputStream getInputStreamOfData(type param) {
    // ..... data 
    OutputStreamWriter writer = new OutputStreamWriter();
    writer.write(data);
    // convert writer object to an InputStream 
}

I came across some libraries to do this such as IOUtils and other thread based methods. Is there a simple way to achieve this using standard Java library ? I want to return the contents in the writer as an InputStream to be consumed by the calling method.

Thanks!

like image 229
Skynet Avatar asked Oct 16 '25 13:10

Skynet


2 Answers

Write to a ByteArrayOutputStream, then get the byte array, and return a ByteArrayInputStream from this byte array.

like image 152
JB Nizet Avatar answered Oct 19 '25 02:10

JB Nizet


I think the correct way to do it is using PipedInputStream. It's just like unix pipes (in highlevel). PipedInputStream constructor takes PipedOutputStream, so if you write to PipedOutputStream, you will get exactly what you want!

Good luck!

like image 32
siemanko Avatar answered Oct 19 '25 03:10

siemanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!