在java.io包中的PipeStream管道流用于在線程之間傳送數(shù)據(jù).一個線程發(fā)送數(shù)據(jù)到輸出管道,另外一個線程從輸入管道中讀取數(shù)據(jù).相關(guān)的類包括: PipedInputStream和PipedOutputStream, PipedReader和PipedWriter。
package com.wkcto.pipestream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 使用PipedInputStream和PipedOutputStream管道字節(jié)流在線程之間傳遞數(shù)據(jù)
* 北京動力節(jié)點老崔
*/
public class Test {
public static void main(String[] args) throws IOException {
//定義管道字節(jié)流
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
//在輸入管道流與輸出管道流之間建立連接
inputStream.connect(outputStream);
//創(chuàng)建線程向管道流中寫入數(shù)據(jù)
new Thread(new Runnable() {
@Override
public void run() {
writeData(outputStream);
}
}).start();
//定義線程從管道流讀取數(shù)據(jù)
new Thread(new Runnable() {
@Override
public void run() {
readData(inputStream);
}
}).start();
}
//定義方法向管道流中寫入數(shù)據(jù)
public static void writeData(PipedOutputStream out ){
try {
//分別把0~100之間的數(shù)寫入管道中
for (int i = 0; i < 100; i++) {
String data = "" + i;
out.write( data.getBytes() ); //把字節(jié)數(shù)組寫入到輸出管道流中
}
out.close(); //關(guān)閉管道流
} catch (IOException e) {
e.printStackTrace();
}
}
//定義方法從管道流中讀取數(shù)據(jù)
public static void readData(PipedInputStream in ){
byte[] bytes = new byte[1024];
try {
//從管道輸入字節(jié)流中讀取字節(jié)保存到字節(jié)數(shù)組中
int len = in.read(bytes); //返回讀到的字節(jié)數(shù),如果沒有讀到任何數(shù)據(jù)返回-1
while ( len != -1 ){
//把bytes數(shù)組中從0開始講到的len個字節(jié)轉(zhuǎn)換為字符串打印
System.out.println( new String(bytes, 0 , len));
len = in.read(bytes); //繼續(xù)從管道中讀取數(shù)據(jù)
}
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字符管道流
* 北京動力節(jié)點老崔
*/
public class Test2 {
public static void main(String[] args) throws IOException {
//先創(chuàng)建字符管道流
PipedReader reader = new PipedReader();
PipedWriter writer = new PipedWriter();
//在輸入管道流與輸出管道流之間建立連接
reader.connect(writer);
//創(chuàng)建一個線程向管道流中穿入數(shù)據(jù)
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();
//開啟另外一個 線程從管道流中讀取數(shù)據(jù)
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();
}
}