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

try {<br />

// So that the buffer doesn't have to be resized,<br />

// we calculate in advance the size of the necessary byte array.<br />

ByteArrayOutputStream bout = new ByteArrayOutputStream(howMany*4);<br />

DataOutputStream dout = new DataOutputStream(bout);<br />

// First two Fibonacci numbers must be given<br />

// to start the process.<br />

int f1 = 1;<br />

int f2 = 1;<br />

dout.writeInt(f1);<br />

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

dout.writeInt(f2);<br />

}<br />

FileOutputStream fout = new FileOutputStream(outputFile);<br />

fout.write(bout.toByteArray());<br />

fout.flush();<br />

fout.close();<br />

}<br />

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

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

You can use the FileDumper3 program from the last chapter with the -i option to view the<br />

output. For example:<br />

% java FibonacciFile fibonacci.dat 10<br />

% java FileDumper3 -i fibonacci.dat<br />

1<br />

1<br />

2<br />

3<br />

5<br />

8<br />

13<br />

21<br />

34<br />

55<br />

8.3 Communicating Between Threads with Piped Streams<br />

The java.io.PipedInputStream class and java.io.PipedOutputStream class provide a<br />

convenient means to move streaming data from one thread to another. Output from one thread<br />

becomes input for the other thread, as shown in Figure 8.1<br />

135

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

Saved successfully!

Ooh no, something went wrong!