Java管道流PipedStream

管道读取流和管道写入流可以像管道一样对接上,管道读取流就可以读取管道写入流写入的数据。需要注意的是需要加入多线程技术,因为单线程,先执行read,会发生死锁,因为read方法是阻塞式的,没有数据的read方法会让线程一直等待。

具体代码及测试

 1 package FileDemo;
 2 
 3 import java.io.IOException;  4 import java.io.PipedInputStream;  5 import java.io.PipedOutputStream;  6  7 public class PipedStreamDemo {  8  9 /** 10  * @param args 11  * @throws IOException 12 */ 13 public static void main(String[] args) throws IOException { 14 15 PipedInputStream pipin = new PipedInputStream(); 16 PipedOutputStream pipout = new PipedOutputStream(); 17  pipin.connect(pipout); 18 new Thread(new Input(pipin)).start(); 19 new Thread(new Output(pipout)).start(); 20  } 21 22 } 23 24 class Output implements Runnable {// 管道写入流 25 private PipedOutputStream out; 26 27  Output(PipedOutputStream out) { 28 this.out = out; 29  } 30 31  @Override 32 public void run() { 33 try { 34 // Thread.sleep(50); 35 out.write("管道流PipedStream".getBytes());// 字节输出流不可以直接写入字符串 36 } catch (Exception e) { 37 // TODO: handle exception 38  } 39  } 40 } 41 42 class Input implements Runnable {// 管道读取流 43 private PipedInputStream in; 44 45  Input(PipedInputStream in) { 46 this.in = in; 47  } 48 49  @Override 50 public void run() { 51 try { 52 byte[] buf = new byte[1024]; 53 int len = 0; 54 len = in.read(buf); 55 System.out.println(new String(buf, 0, len)); 56  in.close(); 57 } catch (Exception e) { 58 // TODO: handle exception 59  } 60  } 61 62 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值