管道流---输入流与输出流结合
A线程负责往管道中写数据
B线程负责从管道中读数据
package com.gc.stream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 管道流
* 将输入流与输出流进行结合
* A线程负责写,B线程负责读
* 必须用多线程,一个线程用来写,另一个线程用来读
*
* @author Administrator
*
*/
public class PipedStreamDemo {
public static void main(String[] args) throws IOException {
//创建输出管道流---将数据写入到管道中
PipedOutputStream pipeOut = new PipedOutputStream();
//创建输入管道流---从管道中读数据
PipedInputStream pipeIn = new PipedInputStream();
//使用管道将输出流与输入流进行连接
pipeIn.connect(pipeOut);
//负责写的线程
new Thread(new Outter(pipeOut)).start();
//负责读的线程
new Thread(new Inner(pipeIn)).start();
}
}
/**
* 负责读取数据,往管道中写的线程
*
*/
class Outter implements Runnable {
private PipedOutputStream out;
public Outter(PipedOutputStream out) {
this.out = out;
}
@Override
public void run() {
String data = "有点郁闷";
try {
out.write(data.getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 负责从管道中读取数据数据的线程
*
*/
class Inner implements Runnable {
private PipedInputStream in;
public Inner(PipedInputStream in) {
this.in = in;
}
@Override
public void run() {
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
String data = new String(buf,0,len);
System.out.println("从管道流中读取到数据:"+data);
} catch (IOException e) {
e.printStackTrace();
}
}
}