If you have used java IO programming, you will soon encounter this situation. A Class creates data on OutputStream and you need to send it to a class that needs to read data from the input stream.
You will soon be asked, "How do I convert OutputStream to InputStream in java ?"
Method 1: use byte array to cache data
The simplest method is to cache data using Byte arrays. Code
ByteArrayOutputStream out = new ByteArrayOutputStream ();
Class1.putDataOnOutputStream (out );
Class2.processDataFromInputStream (
New ByteArrayInputStream (out. toByteArray ())
);
Therefore, OutputStream is converted to InputStream.
Method 2: Use Pipelines
The problem with the first method is that you must have enough memory to cache all data. You can use the File System to cache more data, but the size of data that can be processed is still limited.
The solution is to create a thread to generate data to PipedOutputStream. The current thread can read data from it.
PipedInputStream in = new PipedInputStream ();
PipedOUtputStream out = new PipedOutputStream (in );
New Thread (
New Runnable (){
Public void run (){
Class1.putDataOnOutputStream (out );
}
}
). Start ();
Class2.processDataFromInputStream (in); |
Method 3: Use the circular cache area
The two pipeline streams in method 2 actually manage a hidden circular cache area. Using an explicit circular cache area is easier to understand. CircularBuffers has the following advantages:
One CircularBuffers class instead of two MPs queue classes.
This method is easier to use than caching all data and additional threads.
You can change the cache size without being limited by the fixed cache size of 1 K in the pipeline cache area.
Multithreading:
CircularByteBuffer cbb = new CircularByteBuffer ();
New Thread (
New Runnable (){
Public void run (){
Class1.putDataOnOutputStream (cbb. getOutputStream ());
}
}
). Start ();
Class2.processDataFromInputStream (cbb. getInputStream ());
Single thread
// 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 ());
Author: "zhujianjia"