您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
【第12章:JAVA IO】_管道流
发布时间:2020-12-28 14:11:12编辑:雪饮阅读()
PipedOutputStream、PipedInputStream类提供管道输入输出流。
管道输入输出的实现依赖于多个线程,实现时必须有一个管道输出流和管道输入流,然后在具体调用处先将管道输出流线程中的管道输出流实例与管道输入流线程中的管道输入流实例连接然后在启动两个线程即可。
import java.io.*;
class Send implements Runnable{
// 管道输出流
private PipedOutputStream pos = new PipedOutputStream();
public void run(){
String str = "Hello kasumi!!!" ;
try{
//写入到此线程管道输出流
this.pos.write(str.getBytes()) ;
this.pos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
}
//获取此线程的管道输出流
public PipedOutputStream getPos(){
return this.pos ;
}
};
class Receive implements Runnable{
// 管道输入流
private PipedInputStream pis = new PipedInputStream();
public void run(){
byte b[] = new byte[1024] ; // 接收内容
int len = 0 ;
try{
//从管道输入流读取内容
len = this.pis.read(b);
this.pis.close();
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println("接收的内容为:" + new String(b,0,len)) ;
}
//获取此线程的管道输入流
public PipedInputStream getPis(){
return this.pis ;
}
};
public class Hello{
public static void main(String args[]){
Send s = new Send() ;
Receive r = new Receive() ;
try{
//管道输出流线程连接到管道输入流线程
s.getPos().connect(r.getPis());
}catch(IOException e){
e.printStackTrace() ;
}
new Thread(s).start();
new Thread(r).start();
}
};
关键字词:java,管道,流