读书人

java IO源之管道流

发布时间: 2012-09-20 09:36:50 作者: rapoo

java IO流之管道流
管道流顾名思义就是让流在两根管道里面进行传输,例如将两根管子接到一块,向一根管子输入水,另一根管子就能接到水。管道流也一样。

例如下面的例子,有两个管道流,开两个线程,一个线程向一个管道流里面写入数据,另外一个线程从另一个管道流里面读取数据。看是否读到?答案是肯定的。

package com.unis.io;import java.io.IOException;import java.io.PipedReader;import java.io.PipedWriter;import java.text.SimpleDateFormat;import java.util.Date;public class PipReader {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {final PipedWriter writer = new PipedWriter();final PipedReader reader = new PipedReader(writer);Thread readerT  = new Thread(){@Overridepublic void run() {int i=0;try {while(true){char[] buff = new char[100];while((i=reader.read(buff))!=-1){for(int j=0;j<i;j++){System.out.print(buff[j]);}}}} catch (IOException e) {e.printStackTrace();}finally{try {reader.close();} catch (IOException e) {e.printStackTrace();}}}};Thread writerT  = new Thread(){@Overridepublic void run() {try {while(true){Date d = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String now = sdf.format(d);writer.write(now+"\n");writer.flush();Thread.sleep(1000);}} catch (Exception e) {e.printStackTrace();}finally{try {writer.close();} catch (IOException e) {e.printStackTrace();}}}};readerT.start();writerT.start();}}

读书人网 >软件架构设计

热点推荐