📜  Java I/O-PipedReader

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

Java-PipedReader

PipedReader类用于以字符流的形式读取管道的内容。此类通常用于读取文本。

PipedReader类必须连接到相同的PipedWriter,并且由不同的线程使用。

建设者

Constructor Description
PipedReader(int pipeSize) It creates a PipedReader so that it is not yet connected and uses the specified pipe size for the pipe’s buffer.
PipedReader(PipedWriter src) It creates a PipedReader so that it is connected to the piped writer src.
PipedReader(PipedWriter src, int pipeSize) It creates a PipedReader so that it is connected to the piped writer src and uses the specified pipe size for the pipe’s buffer.
PipedReader() It creates a PipedReader so that it is not yet connected.

方法

Modifier and Type Method Method
void close() It closes this piped stream and releases any system resources associated with the stream.
void connect(PipedWriter src) It causes this piped reader to be connected to the piped writer src.
int read() It reads the next character of data from this piped stream.
int read(char[] cbuf, int off, int len) It reads up to len characters of data from this piped stream into an array of characters.
boolean ready() It tells whether this stream is ready to be read.

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