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.

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {<br />

// probably just an end of stream exception<br />

}<br />

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

Example 8.5 is the FibonacciDriver class. It creates a piped output stream and a piped input<br />

stream and uses those to construct FibonacciWriter and FibonacciReader objects. These<br />

streams are a channel of communication between the two threads. As data is written by the<br />

FibonacciWriter thread it becomes available for the FibonacciReader thread to read. Both<br />

the FibonacciWriter and the FibonacciReader are run with normal priority so when the<br />

FibonacciWriter blocks or is preempted, the FibonacciReader runs and vice versa.<br />

Example 8.5. The FibonacciDriver Class<br />

import java.io.*;<br />

public class FibonacciDriver {<br />

}<br />

public static void main (String[] args) {<br />

}<br />

int howMany;<br />

try {<br />

howMany = Integer.parseInt(args[0]);<br />

}<br />

catch (Exception e) {<br />

howMany = 20;<br />

}<br />

try {<br />

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

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

FibonacciWriter fw = new FibonacciWriter(pout, howMany);<br />

FibonacciReader fr = new FibonacciReader(pin);<br />

fw.start();<br />

fr.start();<br />

}<br />

catch (<strong>IO</strong>Exception e) { System.err.println(e);}<br />

You may be wondering how the piped streams differ from the stream copiers presented earlier<br />

in the book. The first difference is that the piped stream moves data from an output stream to<br />

an input stream. The stream copier always moves data in the opposite direction, from an input<br />

stream to an output stream. The second difference is that the stream copier actively moves the<br />

data by calling the read() and write() methods of the underlying streams. A piped output<br />

stream merely makes the data available to the input stream. It is still necessary for some other<br />

object to invoke the piped input stream's read() method to read the data. If no other object<br />

reads from the piped input stream, then after about one kilobyte of data has been written onto<br />

the piped output stream, the writing thread will block while it waits for the piped input<br />

stream's buffer to empty out.<br />

139

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

Saved successfully!

Ooh no, something went wrong!