In this tutorial we will discuss about the PipedOutputStream.
java.io package contains a class PipedOutputStream which can be connected to the PipedInputStream, used for creating communication pipe. In the PipedOutputStream data is written by a thread which is send to the connected PipedInputStream to read the data bytes, these data bytes of PipedInputStream is read by the other thread. Objects of both PipedInputStream and PipedOutputStream should not be used by a single thread this may cause a deadlocking of thread. If the pipe (which provides the data bytes to the connected piped input stream) is not longer alive then the pipe is called broken.
There are two constructors of PipedOutputStream to create its object :
| PipedOutputStream() | This is a default constructor which creates piped output stream. |
| PipedOutputStream(PipedInputStream snk) | This constructor creates a piped output stream which contains the reference of PipedInputStream. This object is connected to the piped input stream. |
Methods of PipedOutputStream
Commonly used methods of PipedOutputStream are as follows :
Example :
Here I am giving a simple example which demonstrates that how to write bytes to the piped output stream. In this example you will see that the piped output stream is connected to the piped input stream by using the method connect(). Then write the bytes to the piped output stream using write(int b) method and read these written bytes i.e. read the piped input stream bytes using the read(int b) method of PipedInputStream. As result I have format the output i.e. converted the written bytes into the corresponding characters by wrapping the integer value with 'char'.
Source Code :
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.IOException;
public class PipedOutputStreamExample
{
public static void main(String[] args)
{
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try {
//connect the piped output stream with piped input stream
pos.connect(pis);
// Write to the PipedOutputStream
pos.write(82);
pos.write(79);
pos.write(83);
pos.write(69);
pos.write(73);
pos.write(78);
pos.write(68);
pos.write(73);
pos.write(65);
// read the PipedInputStream
int c;
System.out.println();
System.out.println("Written bytes are converted to the corresponding character : ");
System.out.println();
while((c = pis.read() ) != -1)
{
System.out.print((char) c);
}
}
catch (IOException ioe)
{
System.out.println(ioe);
}
}// main closed
}// class closed
Output :
When you will execute the above example you will get the output as follows :

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java PipedOutputStream
Post your Comment