Search code examples
javaioinputstream

Multiple readers for InputStream in Java


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 write incoming data to a StringBuffer or StringBuilder, and have the multiple readers read that. Unfortunately, StringBufferInputStream is deprecated. StringReader reads a string, not a mutable object that's continuously being updated. What are my options? Write my own?


Solution

  • Input stream work like this: once you read a portion from it, it's gone forever. You can't go back and re-read it. what you could do is something like this:

    class InputStreamSplitter {
      InputStreamSplitter(InputStream toReadFrom) {
        this.reader = new InputStreamReader(toReadFrom);
      }
      void addListener(Listener l) {
        this.listeners.add(l);
      }
      void work() {
        String line = this.reader.readLine();
            while(line != null) {
          for(Listener l : this.listeners) {
            l.processLine(line);
          }
        }
      }
    }
    
    interface Listener {
      processLine(String line);
    }
    

    have all interested parties implement Listener and add them to InputStreamSplitter