📜  Java I/O-PipedWriter

📅  最后修改于: 2020-09-27 07:27:31             🧑  作者: Mango

Java-PipedWriter

PipedWriter类用于将Java管道作为字符流编写。此类通常用于编写文本。通常,PipedWriter连接到PipedReader,并由不同的线程使用。

建设者

Constructor Description
PipedWriter() It creates a piped writer that is not yet connected to a piped reader.
PipedWriter(PipedReader snk) It creates a piped writer connected to the specified piped reader.

方法

Modifier and Type Method Method
void close() It closes this piped output stream and releases any system resources associated with this stream.
void connect(PipedReader snk) It connects this piped writer to a receiver.
void flush() It flushes this output stream and forces any buffered output characters to be written out.
void write(char[] cbuf, int off, int len) It writes len characters from the specified character array starting at offset off to this piped output stream.
void write(int c) It writes the specified char to the piped output stream.

import java.io.PipedReader;
import java.io.PipedWriter;

public class PipeReaderExample2 {
public static void main(String[] args) {
try {

final PipedReader read = new PipedReader();
final PipedWriter write = new PipedWriter(read);

Thread readerThread = new Thread(new Runnable() {
public void run() {
try {
int data = read.read();
while (data != -1) {
System.out.print((char) data);
data = read.read();
}
} catch (Exception ex) {
}
}
});

Thread writerThread = new Thread(new Runnable() {
public void run() {
try {
write.write("I love my country\n".toCharArray());
} catch (Exception ex) {
}
}
});

readerThread.start();
writerThread.start();

} catch (Exception ex) {
System.out.println(ex.getMessage());
}

}
}

输出:

I love my country