Multiple readers for InputStream in Java

前端 未结 7 987
名媛妹妹
名媛妹妹 2020-12-03 11:28

I have an InputStream from which I\'m reading characters. I would like multiple readers to access this InputStream. It seems that a reasonable way to achieve this is to writ

7条回答
  •  被撕碎了的回忆
    2020-12-03 11:44

    Note: My other answer is more general (and better in my opinion).

    As noted by @dimo414, the answer below requires the first reader to always be ahead of the second reader. If this is indeed the case for you, then this answer might still be preferable since it builds upon standard classes.


    To create two readers that read independently from the same source, you'll have to make sure they don't consume data from the same stream.

    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
    

提交回复
热议问题