Java Reference
In-Depth Information
Using Pipes
A pipe connects an input stream and an output stream. A piped I/O is based on the producer-consumer pattern,
where the producer produces data and the consumer consumes the data, without caring about each other. It works
similar to a physical pipe, where you inject something at one end and gather it at the other end. In a piped I/O,
you create two streams representing two ends of the pipe. A PipedOutputStream object represents one end and a
PipedInputStream object the other end. You connect the two ends using the connect() method on the either object.
You can also connect them by passing one object to the constructor when you create another object. You can imagine
the logical arrangement of a piped input stream and a piped output stream as depicted in Figure 7-7 .
PipedOutputStream
(Write data to it)
Pipe
(The connection)
PipedInputStream
(Read data from it)
Figure 7-7. The logical arrangement of piped input and output streams
The following snippet of code shows two ways of creating and connecting the two ends of a pipe:
// Method #1: Create piped input and output streams and connect them
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos); /* Connect the two ends */
// Method #1: Create piped input and output streams and connect them
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
You can produce and consume data after you connect the two ends of the pipe. You produce data by using
one of the write() methods of the PipedOutputStream object. Whatever you write to the piped output stream
automatically becomes available to the piped input stream object for reading. You use the read() method of
PipedInputStream to read data from the pipe. The piped input stream is blocked if data is not available when it
attempts to read from the pipe.
Have you wondered where the data is stored when you write it to a piped output stream? Similar to a physical
pipe, a piped stream has a buffer with a fixed capacity to store data between the time it is written to and read from
the pipe. You can set the pipe capacity when you create it. If a pipe's buffer is full, an attempt to write on the pipe
will block.
// Create piped input and output streams with the buffer capacity of 2048 bytes
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos, 2048);
 
 
Search WWH ::




Custom Search