Java TeeOutputStream-class And Method Code Example


Here is an example of using the TeeOutputStream class from the org.apache.commons.io package in Java to write data to multiple OutputStreams:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.output.TeeOutputStream;

public class TeeOutputStreamExample {
    public static void main(String[] args) throws IOException {
        // File to write to
        File outputFile1 = new File("output1.txt");
        File outputFile2 = new File("output2.txt");
        // Create FileOutputStreams for the files
        FileOutputStream fos1 = new FileOutputStream(outputFile1);
        FileOutputStream fos2 = new FileOutputStream(outputFile2);
        // Create a TeeOutputStream
        TeeOutputStream tos = new TeeOutputStream(fos1, fos2);

        // Write to the TeeOutputStream
        tos.write("Hello World!".getBytes());
        // Close the TeeOutputStream
        tos.close();
    }
}

In this example, two FileOutputStreams are created for the files "output1.txt" and "output2.txt", and a TeeOutputStream is created to write to both of them. The TeeOutputStream is then used to write the string "Hello World!" to both files.

This class is useful when you need to write the same data to multiple output streams, for example, when you want to write a log file to both a