Multiple readers for InputStream in Java

前端 未结 7 963
名媛妹妹
名媛妹妹 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 12:04

    Here's another way to read from two streams independently, without presuming one is ahead of the other, but with standard classes. It does, however, eagerly read from the underlying input stream in the background, which may be undesirable, depending on your application.

    public static void main(String[] args) throws IOException {
      // Create the source input stream.
      InputStream is = new ByteArrayInputStream("line1\nline2\nline3".getBytes());
    
      // Create a piped input stream for each reader;
      PipedInputStream in1 = new PipedInputStream();
      PipedInputStream in2 = new PipedInputStream();
    
      // Start copying the input stream to both piped input streams.
      startCopy(is, new TeeOutputStream(
          new PipedOutputStream(in1), new PipedOutputStream(in2)));
    
      // Create the two buffered readers.
      BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
      BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
    
      // Do some interleaved reads from them.
      // ...
    }
    
    private static void startCopy(InputStream in, OutputStream out) {
      (new Thread() {
        public void run() {
          try {
            IOUtils.copy(in, out);
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
      }).start();
    }
    
    0 讨论(0)
提交回复
热议问题