Java TeeReader-class And Method Code Example

Here is an example of how to use the TeeReader class from the Apache Commons IO library to copy the data from a Reader to multiple Writer in Java:



public class TeeReaderExample {
    public static void main(String[] args) throws IOException {
        FileReader inputReader = new FileReader(new File("path/to/file.txt"));
        FileWriter outputWriter1 = new FileWriter(new File("path/to/copy1.txt"));
        FileWriter outputWriter2 = new FileWriter(new File("path/to/copy2.txt"));
        TeeReader teeReader = new TeeReader(inputReader, outputWriter1, outputWriter2);

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


In this example, the TeeReader class is used to copy the data from a file reader to two file writers. The input reader is created to read from a file located at "path/to/file.txt" and the two output writers 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 reader and write it to the output writers. The method returns -1 when the end of the stream is reached.

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

It is important to note that the TeeReader class doesn't buffer the data, so it writes the data as it is read, this may affect performance if you are working with large files.