Java PipedInputStream and PipedOutputStream

In this section we will discuss about the PipedInputStream and
PipedOutputStream in Java.

PipedInputStream and PipedOutputStream both are the Java classes provided in
the java.io package. PipedOutputStream class writes the bytes data into the
piped output stream and PipedInputStream reads the bytes data from the piped
input stream. For writing to and reading from the streams the two individual
threads are involved. One thread writes the bytes to the piped output stream and
the other reads the bytes from the piped input stream. Never should try to use
both PipedOutputStream and PipedInputStream object in a single thread this may
cause for deadlocking of the thread. Actually the PipedOutputStream is a sender
end of pipe which sends the data to the PipedInputStream end which is a receiver
end, after writing the data bytes to the piped output stream then the
PipedInputStream reads that data but, only when the piped input stream and piped
output stream is connected to each other and createad a communication pipe.

Example :

An example is being given here into which I have used the both classes
mentioned above. By giving this example I have tried to demonstrate you about
how the data bytes are written into the piped output stream using one thread and
how the other thread reads the data bytes from the piped input stream. In this
example I have created a class named WriteFileOutputStreamExample1 which extends
the Thread class. WriteFileOutputStreamExample1 first reads the data of a text
file named 'abc.txt' and write them to the new text file named 'xyz.txt'. Again
created a class named InputStreamExample which also extends the Thread class.
The InputStreamExample class reads the bytes written into the 'xyz.txt' file.
Then created a main class named PipedInputOutputStreamExample where created the
objects of PipedOutputStream class and PipedInputStream class. In the
PipedInputStream class object passes the reference of PipedOutputStream class to
make a connection between both objects because the data can be read only when
the communication pipe is created between the both objects.