开发者学堂课程【Java 高级编程:管道流】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/20/detail/324
管道流
内容简介:
1. 管道流介绍
2. 管道流的分类
3. 范例:实现管道操作
管道流介绍
实现两个线程之间的 IO 处理操作
管道流的分类
对于管道流也是分为两类:
· 字节管道流:PipedOutputStream、PipedInputStream;
连接处理:public void connect(PipedInputStream snk)throws IOException;
· 字符管道流:PipedWriter、PipedReader。
连接处理:public void connect(PipedReader snk)throws IOException
范例:实现管道操作
package cn.mldn.demo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java. io. Pipedoutputstream;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception{SendThreadsend = new SendThread();
ReceiveThread receive = new ReceiveThread();
send.getoutput().connect(receive.getInput());//进行管道连接
new Thread(send,"消息发送线程").start();
new Thread(receive,"消息接收线程").start();
}
class SendThread implements Runnable {
privatePipedoutputstream output;//管道的输出流
public SendThread(){
this.output=new Pipedoutputstream();//实例化管道输出流
}
public void run(){
for (int x = 0; x < 10; x++) {try{//利用管道实现数据的发送处理
this.output.write(
(“【第”+(x+1)+“次信息发送-”+Thr
www.mldn.cn\n").getBytes());
}catch (IOException e) {
e.printstackTrace();
}
}
try {
this.output.close();
}catch (IOException e) {
e.printstackTrace();
}
}
public PipedOutputStream getOutput(){}
return output;
}
}
class ReceiveThread implements Runnable
{private PipedInputStream input;
public ReceiveThread(){
this.input = new PipedInputStream();
}
this.output.close();
}catch (IOException e) {
e.printstackTrace();
}
}
public PipedOutputStream getOutput(){
return output;
}
class ReceiveThread implements Runnable {
privatePipedInputStream input;
public ReceiveThread(){
this.input = new PipedInputStream();
}
@Override.
public void run(){
byte data[]=new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream()
try{
while ( (len = this. input. read (data)! =- 1) {
bos.write(data,e,len);//所有的数据保存到内存流System.out.println("{"+Thread.currentThread().getN String(bos.toByteArray()));
bos.close();
}catch (IOException e) {
e.printstackTrace();
}
}
public PipedInputstream getInput(){
return input;
}
管道就类似于医院打点滴效果,一个只是负责发送,一个负责接收,中间靠一个管道连接。