Java IO: PipedInputStream
Jakob Jenkov |
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.
| Tweet | |
Jakob Jenkov | |











