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 />

public FibonacciWriter(OutputStream out, int howMany)<br />

throws <strong>IO</strong>Exception {<br />

theOutput = new DataOutputStream(out);<br />

this.howMany = howMany;<br />

}<br />

public FibonacciWriter(OutputStream out) throws <strong>IO</strong>Exception {<br />

this(out, Integer.MAX_VALUE);<br />

}<br />

public void run() {<br />

}<br />

try {<br />

int f1 = 1;<br />

int f2 = 1;<br />

theOutput.writeInt(f1);<br />

theOutput.writeInt(f2);<br />

// Now calculate the rest.<br />

for (int i = 2; i < howMany; i++) {<br />

int temp = f2;<br />

f2 = f2 + f1;<br />

f1 = temp;<br />

if (f2 < 0) { // overflow<br />

break;<br />

}<br />

theOutput.writeInt(f2);<br />

}<br />

}<br />

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

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

Example 8.4 is the FibonacciReader class. It could just as well have been called the<br />

IntegerReader class, since it doesn't know anything about Fibonacci numbers. Its run()<br />

method merely reads integers from its input stream until the stream is exhausted or an<br />

<strong>IO</strong>Exception is thrown.<br />

Example 8.4. The FibonacciReader Class<br />

import java.io.*;<br />

public class FibonacciReader extends Thread {<br />

DataInputStream theInput;<br />

public FibonacciReader(InputStream in)<br />

throws <strong>IO</strong>Exception {<br />

theInput = new DataInputStream(in);<br />

}<br />

public void run() {<br />

try {<br />

while (true) {<br />

System.out.println(theInput.readInt());<br />

}<br />

}<br />

138

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

Saved successfully!

Ooh no, something went wrong!