Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

StreamGobbler



The StreamGobbler class constantly consumes the input from an InputStream, and distribute the input lines to a listener. This is often useful when using ProcessBuilder and listen to the InputStream coming from the external process, but you can use it with any InputStream.

Contrary to many implementations seen on the Web, this class defer the actual work to a listener.

If you want to listen to both the output stream and the error stream of a Process, it will be easier to use directly the ProcessHandler class. Note that the output stream of the process will be connected to the Process.getInputStream() which is why the argument in the StreamGobbler is an InputStream.


It is possible when creating the StreamGobbler to specify a Charset to read the InputStream. By default the UTF-8 charset will be used.

Listener interface

The StreamGobbler.Listener interface has two methods:
By default the listener is called in the same Thread as the reading of the InputStream, which means that if the stream receives a lot of inputs in a short time, some of them could be discarded by the listener, leading to problems. You can handle the listener in another thread to avoid this problem.


streamgobbler1

Usage

After the creation of the StreamGobbler:
It will not be possible to configure the behavior after it has been started.

Stopping the reading

You can force top the reading of the stream with the StreamGobbler.stop() method. However the reading will stop as soon as the stream return a null String. In that case the StreamGobbler.Listener.close() method will be called.

Handling the listener in another thread

By default the listener is called in the same Thread as the reading of the InputStream, which means that if the stream receives a lot of inputs in a short time, some of them could be discarded by the listener, leading to problems.

The following methods allow to handle the StreamGobbler.Listener.readLine(String) method in another Thread using a Queue, which ensures that no event in the InputStream readings will be discarded:
streamgobbler2

Example

The following code will redirect the output of an executable (normally on the console) to a List of Strings:
   ProcessBuilder pb = new ProcessBuilder("my_executable.exe");
   Process process = pb.start();
      
   StreamGobbler outgobbler = new StreamGobbler(process.getInputStream());
   List<String> lines = new ArrayList<>
   outgobbler.setListener(new StreamGobbler.Listener() {
      @Override
      public void readLine(String line) {
        lines.add(line);
      }

      @Override
      public void close() {
      }
   });
   errorgobbler.start();
   outgobbler.start();

See also


Categories: Io | Packages

Copyright 2006-2024 Herve Girod. All Rights Reserved. Documentation and source under the LGPL v2 and Apache 2.0 licences