Tech and Media Labs
This site uses cookies to improve the user experience.




Java IO: PipedWriter

Jakob Jenkov
Last update: 2015-09-07

The Java PipedWriter class (java.io.PipedWriter) makes it possible to write to a Java pipe as a stream of characters. In that respect the PipedWriter works much like a PipedOutputStream except that a PipedOutputStream is byte based, whereas a PipedWriter is character based. The PipedWriter is intended for writing text, in other words.

Normally a Java PipedWriter is connected to a PipedReader. And often the PipedWriter and the PipedReader are used by different threads.

PipedWriter Example

Here is a simple Java PipedWriter example:

PipedWriter pipedWriter = new PipedWriter();

while(moreData()) {
  int data = getMoreData();
  pipedWriter.write(data);
}
pipedWriter.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

write()

The write() method of a PipedWriter takes an int which contains the byte value of the byte to write. There are also versions of the write() method that take a String, char array etc.

Java IO Pipes

The PipedWriter must always be connected to a PipedReader. When connected like that, they form a Java pipe. To learn more about Java pipes, go to Java IO: Pipes.

Closing a PipedWriter

When you are finished writing characters to a Java PipedWriter you should remember to close it. Closing a PipedWriter is done by calling its close() method. Here is how closing a Java PipedWriter looks:

pipedWriter.close();

You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a PipedWriter looks with the try-with-resources construct:

try(PipedWriter pipedWriter =
    new PipedWriter(){

    pipedWriter.write("data 1");
    pipedWriter.write("data 2");
    pipedWriter.write("data 3");

}

Notice how there is no longer any explicit close() method call to the PipedWriter instance. The try-with-resources construct takes care of that.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC