Java IO: PipedInputStream

Jakob Jenkov
Last update: 2014-11-15

The PipedInputStream class makes it possible to read the contents of a pipe as a stream of bytes. Pipes are communication channels between threads inside the same JVM. Pipes are explained in more detail in my tutorial about Java IO Pipes.

PipedInputStream Example

Here is a simple PipedInputStream example:

InputStream input = new PipedInputStream(pipedOutputStream);

int data = input.read();
while(data != -1) {
  //do something with data...
  doSomethingWithData(data);

  data = input.read();
}
input.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.

The read() method of a PipedInputStream returns an int which contains the byte value of the byte read. If the read() method returns -1, there is no more data to read in the stream, and it can be closed. That is, -1 as int value, not -1 as byte value. There is a difference here!

More PipedInputStream Methods

Since PipedInputStream is a subclass of InputStream, PipedInputStream has the same basic methods and use patterns as an InputStream. See my InputStream tutorial for more information.

Java IO Pipes

As you can see in the example above, a PipedInputStream needs to be connected to a PipedOutputStream. When these two streams are connected they form a pipe. To learn more about Java IO pipes, go to Java IO: Pipes.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next