23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 8.1. Data moving between threads with piped streams<br />

public class PipedInputStream extends InputStream<br />

public class PipedOutputStream extends OutputStream<br />

The PipedInputStream class has two constructors:<br />

public PipedInputStream()<br />

public PipedInputStream(PipedOutputStream source) throws <strong>IO</strong>Exception<br />

<strong>Java</strong> I/O<br />

The no-argument constructor creates a piped input stream that is not yet connected to a piped<br />

output stream. The second constructor creates a piped input stream that's connected to the<br />

piped output stream source.<br />

The PipedOutputStream class also has two constructors:<br />

public PipedOutputStream(PipedInputStream sink) throws <strong>IO</strong>Exception<br />

public PipedOutputStream()<br />

The no-argument constructor creates a piped output stream that is not yet connected to a piped<br />

input stream. The second constructor creates a piped output stream that's connected to the<br />

piped input stream sink.<br />

Piped streams are normally created in pairs. The piped output stream becomes the underlying<br />

source for the piped input stream. For example:<br />

PipedOutputStream pout = new PipedOutputStream();<br />

PipedInputStream pin = new PipedInputStream(pout);<br />

This simple example is a little deceptive, because these lines of code will normally be in<br />

different methods and perhaps even different classes. Some mechanism must be established to<br />

pass a reference to the PipedOutputStream into the thread that handles the<br />

PipedInputStream. Or you can create them in the same thread, then pass a reference to the<br />

connected stream into a separate thread. Alternately, you can reverse the order:<br />

PipedInputStream pin = new PipedInputStream();<br />

PipedOutputStream pout = new PipedOutputStream(pin);<br />

Or you can create them both unconnected, then use one or the other's connect() method to<br />

link them:<br />

PipedInputStream pin = new PipedInputStream();<br />

PipedOutputStream pout = new PipedOutputStream();<br />

pin.connect(pout);<br />

136

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!