Java DemuxOutputStream-class And Method Code Example


Here is an example of using the DemuxOutputStream 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.DemuxOutputStream;

public class DemuxOutputStreamExample {
    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 DemuxOutputStream
        DemuxOutputStream dos = new DemuxOutputStream();
        // Add the FileOutputStreams to the DemuxOutputStream
        dos.addOutputStream(fos1);
        dos.addOutputStream(fos2);

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

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

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 file and to the console. The DemuxOutputStream class allows you to write the data to multiple output streams in a single call, instead of having to write the data to each stream separately.