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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

public class TeeOutputStream extends FilterOutputStream {<br />

}<br />

OutputStream out1;<br />

OutputStream out2;<br />

public TeeOutputStream(OutputStream stream1, OutputStream stream2) {<br />

super(stream1);<br />

out1 = stream1;<br />

out2 = stream2;<br />

}<br />

public synchronized void write(int b) throws <strong>IO</strong>Exception {<br />

out1.write(b);<br />

out2.write(b);<br />

}<br />

public synchronized void write(byte[] data, int offset, int length)<br />

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

out1.write(data, offset, length);<br />

out2.write(data, offset, length);<br />

}<br />

public void flush() throws <strong>IO</strong>Exception {<br />

out1.flush();<br />

out2.flush();<br />

}<br />

public void close() throws <strong>IO</strong>Exception {<br />

out1.close();<br />

out2.close();<br />

}<br />

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

It would be possible to store one of the output streams in FilterOutputStream's protected<br />

out field and the other in a field in this class. However, it's simpler and cleaner to maintain<br />

the parallelism between the two streams by storing them both in the TeeOutputStream class.<br />

I've synchronized the write() methods to make sure that two different threads don't try to<br />

write to the same TeeOutputStream at the same time. Depending on unpredictable threadscheduling<br />

issues, this could lead to data being written out of order or in different orders on<br />

different streams. It's important to make sure that one write is completely finished on all<br />

streams before the next write begins.<br />

Example 6.6 demonstrates how one might use this class to write a TeeCopier program that<br />

copies one file into two separate, new files.<br />

Example 6.6. The TeeCopier Program<br />

import java.io.*;<br />

import com.macfaq.io.*;<br />

86

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

Saved successfully!

Ooh no, something went wrong!