2012-10-23 76 views

回答

4

這裏是在Java中使用PipedReaderPipedWriter的例子:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PipedReader; 
import java.io.PipedWriter; 
/** 
* @date 1st May, 2011 
* @author sanju.org 
* 
* To demonstrate the use of piped character streams. 
* Example program for piped character stream in java. 
* 
*/ 

public class PipedReaderExample { 

    public static void main(String args[]) throws IOException{ 
     PipedReader reader = new PipedReader(); 
     PipedWriter writer = new PipedWriter(reader); 
     Thread readerThread = new Thread(new ReaderThread(writer)); 
     Thread writerThread = new Thread(new WriterThread(reader)); 
     readerThread.start(); 
     writerThread.start(); 
    } 

} 

class ReaderThread implements Runnable{ 
    PipedWriter writer; 
    public ReaderThread(PipedWriter writer){ 
     this.writer = writer; 
    } 

    public void run() { 
     InputStreamReader streamReader = new InputStreamReader(System.in); 
     BufferedReader bufferedReader = new BufferedReader(streamReader); 
     try { 
      while (true) { 
       //sample implementation reading from console 
       //real implementation can be reading from a socket or a file 
       //or from server side code 
       String line = bufferedReader.readLine(); 
       writer.write(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

class WriterThread implements Runnable{ 
    PipedReader reader; 
    public WriterThread(PipedReader reader){ 
     this.reader = reader; 
    } 

    public void run() { 
     while(true){ 
      try { 
       char c; 
       while((c = (char)reader.read()) != -1){ 
        //write your business logic here 
        //could be writing into a file 
        //could be processing the date 
        System.out.println(c); 
       } 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

至於使用雅虎與PipedReader/Writer類我想你會閱讀他們的API連接到URL等

這裏是一個有關PipedReaderPipedWriter(混合教程和信息),這可能是幫助其他鏈接的列表:

至於事物的迴轉側,以顯示從管道接收到的數據就需要使用一個TextComponent像其中的一個:

setText(...)這將允許您設置的內容

參考:

+1

+1 WOW不錯!可能希望在Swing中添加一些關於併發的信息;) – MadProgrammer

+1

+1另請參閱此相關的[示例](http://stackoverflow.com/a/4444677/230513)。 – trashgod

+0

@MadProgrammer一個垃圾桶謝謝你和+1兩個(管道是非常罕見的嘿?!) –