PipedReader and PipedWriter in Java with example

PipedReader and PipedWriter in Java with example

A pipe connects an input stream and an output stream. A piped I/O is based on the producer-consumer pattern, where the producer produces data and the consumer consumes it. In a piped I/O, we create two streams representing two ends of the pipe. A PipedWriter object represents one end of the pipe (sending end) and a PipedReader object represents the other end. We can connect the two ends using the connect() method on either object or by passing one object to the constructor of other object. If this object is already connected to some other object, an IOException is thrown. In this post we will see the usage of PipedReader and PipedWriter in Java with example programs.

PipedReader and PipedWriter class

The Java PipedReader class is used to read the contents of a pipe as a stream of characters. The Java PipedWriter class is used to write to a Java pipe as a stream of characters. A Java PipedReader must be connected to a PipedWriter. Mostly, the PipedReader and PipedWriter are used by different threads running in the same JVM (used for inter thread communication). Only one PipedReader can be connected to the same PipedWriter. Below is a pictorial representation for better understanding.

IO Pipes Java

Java program using PipedReader and PipedWriter

Here is a sample Java program showing the usage of PipedReader and PipedWriter class.

Below is the output of above program.

In the above program, we have created a source thread in which a PipedWriter object writes character equivalent of values 65 through 90 (i.e. A to Z) to the piped output stream. Similarly we also created a destination thread in which a PipedReader object reads the characters from the piped stream. Note that the PipedWriter object in the source thread is connected to the PipedReader object in the destination thread.

The write() method can take an integer value or character array or a string. The read(char[] cbuf, int off, int len) method in the PipedReader object reads up to len characters of data from the piped stream into an array of characters or less than len characters will be read if the end of the data stream is reached.

That’s all about PipedReader and PipedWrite in Java. If you have any doubt, post it in the comments section.

Also read,

PipedInputStream and PipedOutputStream in Java

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.