📅  最后修改于: 2023-12-03 15:31:34.790000             🧑  作者: Mango
Java.io.PipedWriter
类是Java I/O库提供的一个类,属于管道流的一种,用于写入管道输出流的字符流。它和Java.io.PipedReader
配对使用可以实现线程之间的数据交换和通信。
public PipedWriter() throws IOException
public PipedWriter(PipedReader snk) throws IOException
PipedWriter
继承了java.io.Writer
类的所有方法,其中常用的有:
public void write(int c) throws IOException
:向管道写入一个字节。public void write(char[] cbuf, int off, int len) throws IOException
:向管道写入char[]数组的一部分。public void write(String str, int off, int len) throws IOException
:向管道写入字符串的一部分。public void flush() throws IOException
:刷新管道。public void close() throws IOException
:关闭管道。import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipeDemo {
public static void main(String[] args) {
PipedWriter writer = new PipedWriter();
PipedReader reader;
try {
reader = new PipedReader(writer);
new Thread(new WriterThread(writer)).start();
new Thread(new ReaderThread(reader)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
static class WriterThread implements Runnable{
private final PipedWriter writer;
WriterThread(PipedWriter writer) {
this.writer = writer;
}
@Override
public void run() {
String message = "Hello, World!";
try {
writer.write(message);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class ReaderThread implements Runnable{
private final PipedReader reader;
ReaderThread(PipedReader reader) {
this.reader = reader;
}
@Override
public void run() {
int data;
try {
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
该示例程序创建了一个管道,通过PipedWriter
向管道写入了一段字符串,通过PipedReader
读取了该字符串并打印。其中,PipedWriter
和PipedReader
配对使用,确保了在PipedWriter
方向写入数据的同时,PipedReader
方向可以读取该数据。