Java PipedReader class is used to read character data from a pipe as a stream of characters.
In this chapter, we will learn what the PipedReader class is, why it is used, its declaration, constructors, methods, and examples to understand how it works with PipedWriter for inter-thread communication.
The PipedReader class is a character input stream that reads data from a pipe. This data is written to the pipe using a connected PipedWriter.
PipedReader is mainly used for communication between two threads, where one thread writes character data using PipedWriter and another thread reads that data using PipedReader. Both streams must be connected to each other and usually run in different threads.
The PipedReader class is a part of the java.io package and extends the Reader class.
The PipedReader class provides constructors to create a piped reader that may or may not be connected to a piped writer.
This constructor creates a PipedReader that is not yet connected to any PipedWriter.
Syntax:
Here is the syntax:
This constructor creates a PipedReader that is already connected to the specified PipedWriter.
Syntax:
Here is the syntax:
This constrictor creates a PipedReader that is not yet connected and uses the specified pipe size for the internal buffer.
Syntax:
Here is the syntax:
This constructor creates a PipedReader that is connected to the specified PipedWriter and uses the given pipe size.
Syntax:
Here is the syntax:
The following example demonstrates how to create and connect a PipedReader using different constructors.
The PipedReader class provides the following methods to read characters and manage the pipe connection.
| 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. |
Practice the following examples to understand the concept and usages of PipedReader class.
The following example demonstrates how PipedReader reads data written by a PipedWriter using two different threads.
Output:
I love my country
The following example demonstrates how a PipedReader can be connected to a PipedWriter using the connect() method.
Output:
Java PipedReader Example
We request you to subscribe our newsletter for upcoming updates.