Use Commons IO TeeOutputStream
to send the same data to two
instances of OutputStream
. When data
is written to a TeeOutputStream
, that data is sent to the two instances of OutputStream
passed to its constructor. The
following example demonstrates the use of TeeOutputStream
to write the same String
to two instances of FileOutputStream
:
import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.TeeOutputStream; File test1 = new File("split1.txt"); File test2 = new File("split2.txt"); OutputStream outStream = null; try { FileOutputStream fos1 = new FileOutputStream( test1 ); FileOutputStream fos2 = new FileOutputStream( test2 ); outStream = new TeeOutputStream( fos1, fos2 ); outStream.write( "One Two Three, Test".getBytes( ) ); outStream.flush( ); } catch( IOException ioe ) { System.out.println( "Error writing to split output stream" ); } finally { IOUtils.closeQuietly( outStream ); }
Flushing or closing a TeeOutputStream
will flush or close both of
the OutputStream
instances it
contains. After this example is executed, two files, split1.txt
and split2.txt
, will contain the same
text.