The output stream is converted directly to the input streams without the need for file generation. There are three ways to use the following:
If you have ever used Java IO programming, you will soon encounter this situation where a class creates data on OutputStream and you need to send it to a class that needs to read the data from the input stream.
You'll soon be asked, "How do you convert OutputStream to InputStream in Java?" ”
Method One: Use byte arrays to cache data
The simplest method is to cache the data with a byte array. Code
Bytearrayoutputstream out = new Bytearrayoutputstream (); Class1.putdataonoutputstream (out); Class2.processdatafrominputstream (New Bytearrayinputstream (Out.tobytearray ()));
So, OutputStream was converted to InputStream.
Method Two: Using pipelines
The problem with the first approach is that you must have enough memory to cache all the data. You can use the file system to cache more data, but the size of the data can still be limited anyway.
The workaround is to create a thread to produce the data to PipedOutputStream. The current thread can read data from.
PipedInputStream in = new PipedInputStream (); PipedOutputStream out = new PipedOutputStream (in); New Thread (New Runnable () {public void run () {class1.putdataonoutputstream (out); }}). Start (); Class2.processdatafrominputstream (in); | | |
Method Three: Using cyclic buffers
The two pipeline flows in method two actually manage a hidden loop buffer. Using an explicit loop buffer is easier to understand. Circularbuffers has the following advantages
A circularbuffers class instead of two pipe classes.
Easier to use than caching all data and additional threading methods.
You can change the cache size without being limited to the fixed cache size of the pipe buffer 1K.
Multithreading scenario: Circularbytebuffer CBB = new Circularbytebuffer (); New Thread (New Runnable () {public void run () {Class1.putdataonoutputstream (Cbb.getoutputstream ()); }}). Start (); Class2.processdatafrominputstream (Cbb.getinputstream ()); Single thread scenario//buffer all data in a circular buffer of infinite size circularbytebuffer CBB = new Circularbytebuffer (circularb Ytebuffer.infinite_size); Class1.putdataonoutputstream (Cbb.getoutputstream ()); Class2.processdatafrominputstream (Cbb.getinputstream ());
How to convert OutputStream to InputStream in Java