The PipedReader class is utilized for reading character streams from a pipe. It is commonly employed for reading textual information.
The PipedReader class needs to be linked to the corresponding PipedWriter instance and can be accessed by multiple threads.
Constructor
| 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. |
Method
| 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 anarrayof characters. |
| boolean | ready() | It tells whether this stream is ready to be read. |
Example
Example
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());
}
}
}
Output:
Output
I love my country