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.

public class TeeCopier {<br />

}<br />

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

}<br />

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

if (args.length != 3) {<br />

System.out.println("Usage: java TeeCopier infile outfile1 outfile2");<br />

return;<br />

}<br />

try {<br />

FileInputStream fin = new FileInputStream(args[0]);<br />

FileOutputStream fout1 = new FileOutputStream(args[1]);<br />

FileOutputStream fout2 = new FileOutputStream(args[2]);<br />

TeeOutputStream tout = new TeeOutputStream(fout1, fout2);<br />

BufferedStreamCopier.copy(fin, tout);<br />

fin.close();<br />

tout.close();<br />

}<br />

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

It's not hard to extend this to a MultiOutputStream class that handles an arbitrary number of<br />

output streams. You simply need to store the list of output streams in a vector and provide an<br />

addStream() method that adds them to the vector as needed. The methods of the class then<br />

simply enumerate the vector, invoking the method on each element of the vector in turn.<br />

Example 6.7 demonstrates.<br />

Example 6.7. The MultiOutputStream Class<br />

package com.macfaq.io;<br />

import java.io.*;<br />

import java.util.*;<br />

public class MultiOutputStream extends FilterOutputStream {<br />

Vector streams = new Vector();<br />

public MultiOutputStream(OutputStream out) {<br />

super(out);<br />

streams.addElement(out);<br />

}<br />

public synchronized void addOutputStream(OutputStream out) {<br />

streams.addElement(out);<br />

}<br />

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

}<br />

for (Enumeration e = streams.elements(); e.hasMoreElements();) {<br />

OutputStream out = (OutputStream) e.nextElement();<br />

out.write(b);<br />

}<br />

87

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

Saved successfully!

Ooh no, something went wrong!