How can I make a copy of a BufferedReader?

Sunil picture Sunil · Aug 24, 2012 · Viewed 13.8k times · Source

I am using a BufferedReader constructor to make a new copy of an existing BufferedReader.

BufferedReader buffReader = new BufferedReader(originalBuffReader);

The new buffReader is working fine, but when I do originalBuffReader.readLine() it gives me null. Is there any other way I can make a new bufferReader without affecting my original BufferedReader.

FYI: I am getting bufferReader as an input to my method; and I do not have a access to the source.

Answer

aioobe picture aioobe · Aug 24, 2012

Any other way I can make a new bufferReader without affecting my oroginal BufferReader

There's no straight forward way of solving it by just creating two BufferedReaders. (The two readers will consume data from the same source.) You'll have to add another level of buffering on the source, so each reader can read the stream independently.

This can be achieved by combining TeeInputStream from Apache Commons and a PipedInputStream and PipedOutputStream as follows:

import java.io.*;
import org.apache.commons.io.input.TeeInputStream;
class Test {
    public static void main(String[] args) throws IOException {

        // Create the source input stream.
        InputStream is = new FileInputStream("filename.txt");

        // Create a piped input stream for one of the readers.
        PipedInputStream in = new PipedInputStream();

        // Create a tee-splitter for the other reader.
        TeeInputStream tee = new TeeInputStream(is, new PipedOutputStream(in));

        // Create the two buffered readers.
        BufferedReader br1 = new BufferedReader(new InputStreamReader(tee));
        BufferedReader br2 = new BufferedReader(new InputStreamReader(in));

        // Do some interleaved reads from them.
        System.out.println("One line from br1:");
        System.out.println(br1.readLine());
        System.out.println();

        System.out.println("Two lines from br2:");
        System.out.println(br2.readLine());
        System.out.println(br2.readLine());
        System.out.println();

        System.out.println("One line from br1:");
        System.out.println(br1.readLine());
        System.out.println();
    }
}

Output:

One line from br1:
Line1: Lorem ipsum dolor sit amet,      <-- reading from start

Two lines from br2:
Line1: Lorem ipsum dolor sit amet,      <-- reading from start
Line2: consectetur adipisicing elit,

One line from br1:
Line2: consectetur adipisicing elit,    <-- resumes on line 2