程式扎記: [ Java 常見問題 ] Pipe OutputStream with InputStream

標籤

2015年3月30日 星期一

[ Java 常見問題 ] Pipe OutputStream with InputStream

Source From Here
Question
I want to pass an OutputStream to an InputStream in memory without creating a file on the hard disk.

How-To
Below is the sample code using:
BufferedReader(InputStreamReader(PipedInputStream)) (In<--- b=""> (Out)PrintStream(PipedOutputStream(PipedInputStream))
  1. package howto;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.io.PipedInputStream;  
  6. import java.io.PipedOutputStream;  
  7. import java.io.PrintStream;  
  8.   
  9. public class InOut {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         PipedInputStream pin = new PipedInputStream();  
  13.         PipedOutputStream pout = new PipedOutputStream(pin);  
  14.         
  15.         PrintStream out = new PrintStream(pout);  
  16.         BufferedReader in = new BufferedReader(new InputStreamReader(pin));  
  17.         
  18.         System.out.println("Writing to output stream...");  
  19.         out.println("Hello World!");  
  20.         out.flush();  
  21.         
  22.         System.out.println("Text written: " + in.readLine());  
  23.     }  
  24. }  
Execution result:
Writing to output stream...
Text written: Hello World!


沒有留言:

張貼留言

網誌存檔