Java TeeInputStream-class And Method Code Example


Here is an example of how to use the TeeInputStream class from the Apache Commons IO library to copy the data from an input stream to multiple output streams in Java:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.input.TeeInputStream;

public class TeeInputStreamExample {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream(new File("path/to/file.txt"));
        FileOutputStream outputStream1 = new FileOutputStream(new File("path/to/copy1.txt"));
        FileOutputStream outputStream2 = new FileOutputStream(new File("path/to/copy2.txt"));
        TeeInputStream teeInputStream = new TeeInputStream(inputStream, outputStream1, outputStream2);

        int data;
        while ((data = teeInputStream.read()) != -1) {
            // Do something with the data
        }

        teeInputStream.close();
        inputStream.close();
        outputStream1.close();
        outputStream2.close();
    }
}

In this example, the TeeInputStream class is used to copy the data from a file input stream to two file output streams. The input stream is created to read from a file located at "path/to/file.txt" and the two output streams are created to write to two different files located at "path/to/copy1.txt" and "path/to/copy2.txt" respectively.

A while loop is used to read the data from the input stream and write it to the output streams. The teeInputStream.read() method returns -1 when the end of the stream is reached.

Finally, all the streams are closed after reading the file.