摘要:
下文使用Java代码中PipedInputStream和PipedOutputStream类的用法分享,如下所示:
Pipe用于将一个程序的输出发送到另一个程序的输入
注意事项:
PipedInputStream必须连接到PipedOutputStream
PipedOutputStream必须连接到PipedInputStream
例:
Java 中PipedInputStream和PipedOutputStream类的示例
package com.maomao365;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* @author maomao365
*/
public class PipedStreamExample {
public static void main(String[] args) throws IOException InterruptedException {
final PipedInputStream pipedInputStream=new PipedInputStream();
final PipedOutputStream pipedOutputStream=new PipedOutputStream();
/*Connect pipe*/
pipedInputStream.connect(pipedOutputStream);
/*Thread for writing data to pipe*/
Thread pipeWriter=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 80; i++) {
try {
pipedOutputStream.write(i);
Thread.sleep(500);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
});
/*Thread for reading data from pipe*/
Thread pipeReader=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 80; i++) {
try {
System.out.print((char)pipedInputStream.read());
Thread.sleep(1000);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
});
/*Start thread*/
pipeWriter.start();
pipeReader.start();
/*Join Thread*/
pipeWriter.join();
pipeReader.join();
/*Close stream*/
pipedOutputStream.close();
pipedInputStream.close();
}
}