java_IO流のPipedInputStreamパイプ流の使用
パイプストリームは、2つのスレッド間でバイナリデータの伝送を実現することができる.
パイプフローはパイプのようなもので、一端はデータを入力し、他端はデータを出力します.通常は、2つの異なるスレッドで制御します.
使用方法は次のとおりです.
パイプフローはパイプのようなもので、一端はデータを入力し、他端はデータを出力します.通常は、2つの異なるスレッドで制御します.
使用方法は次のとおりです.
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedInputStreamTest {
public static void main(String[] args) {
//
PipedOutputStream out = new PipedOutputStream();
//
PipedInputStream in = null;
try {
// 。 connect(Piped..);
in = new PipedInputStream(out);
Thread read = new Thread(new Read(in));
Thread write = new Thread(new Write(out));
//
read.start();
write.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Write implements Runnable {
PipedOutputStream pos = null;
public Write(PipedOutputStream pos) {
this.pos = pos;
}
public void run() {
try {
System.out.println(" 3 , 。。。");
Thread.sleep(3000);
pos.write("wangzhihong".getBytes());
pos.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (pos != null) {
pos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Read implements Runnable {
PipedInputStream pis = null;
public Read(PipedInputStream pis) {
this.pis = pis;
}
public void run() {
byte[] buf = new byte[1024];
try {
pis.read(buf);
System.out.println(new String(buf));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pis != null) {
pis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}