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!


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...