在java.io包中的PipeStream管道流用于在线程之间传送数据.一个线程发送数据到输出管道,另外一个线程从输入管道中读取数据.相关的类包括: PipedInputStream和PipedOutputStream, PipedReader和PipedWriter。
package com.wkcto.pipestream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 使用PipedInputStream和PipedOutputStream管道字节流在线程之间传递数据
* 北京乐学网老崔
*/
public class Test {
public static void main(String[] args) throws IOException {
//定义管道字节流
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
//在输入管道流与输出管道流之间建立连接
inputStream.connect(outputStream);
//创建线程向管道流中写入数据
new Thread(new Runnable() {
@Override
public void run() {
writeData(outputStream);
}
}).start();
//定义线程从管道流读取数据
new Thread(new Runnable() {
@Override
public void run() {
readData(inputStream);
}
}).start();
}
//定义方法向管道流中写入数据
public static void writeData(PipedOutputStream out ){
try {
//分别把0~100之间的数写入管道中
for (int i = 0; i < 100; i++) {
String data = "" + i;
out.write( data.getBytes() ); //把字节数组写入到输出管道流中
}
out.close(); //关闭管道流
} catch (IOException e) {
e.printStackTrace();
}
}
//定义方法从管道流中读取数据
public static void readData(PipedInputStream in ){
byte[] bytes = new byte[1024];
try {
//从管道输入字节流中读取字节保存到字节数组中
int len = in.read(bytes); //返回读到的字节数,如果没有读到任何数据返回-1
while ( len != -1 ){
//把bytes数组中从0开始讲到的len个字节转换为字符串打印
System.out.println( new String(bytes, 0 , len));
len = in.read(bytes); //继续从管道中读取数据
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.wkcto.pipestream;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.PrintWriter;
/**
* PipedReader与PipedWriter字符管道流
* 北京乐学网老崔
*/
public class Test2 {
public static void main(String[] args) throws IOException {
//先创建字符管道流
PipedReader reader = new PipedReader();
PipedWriter writer = new PipedWriter();
//在输入管道流与输出管道流之间建立连接
reader.connect(writer);
//创建一个线程向管道流中穿入数据
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
writer.write( "data--" + i + "--" + Math.random() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
//开启另外一个 线程从管道流中读取数据
new Thread(new Runnable() {
@Override
public void run() {
char [] charArray = new char[1024];
try {
int len = reader.read(charArray);
while (len != -1 ){
System.out.print( String.valueOf(charArray, 0, len));
len = reader.read(charArray);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}