title: ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread
body: <p>I'm building a process in Java using ProcessBuilder as follows:</p>
  
  <pre><code>ProcessBuilder pb = new ProcessBuilder()
          .command("somecommand", "arg1", "arg2")
          .redirectErrorStream(true);
  Process p = pb.start();
  
  InputStream stdOut = p.getInputStream();
  </code></pre>
  
  <p>Now my problem is the following: I would like to capture whatever is going through stdout and/or stderr of that process and redirect it to <code>System.out</code> asynchronously. I want the process and its output redirection to run in the background.  So far, the only way I've found to do this is to manually spawn a new thread that will continuously read from <code>stdOut</code> and then call the appropriate <code>write()</code> method of <code>System.out</code>. </p>
  
  <pre><code>new Thread(new Runnable(){
      public void run(){
          byte[] buffer = new byte[8192];
          int len = -1;
          while((len = stdOut.read(buffer)) &gt; 0){
              System.out.write(buffer, 0, len);
          }
      }
  }).start();
  </code></pre>
  
  <p>While that approach kind of works, it feels a bit dirty. And on top of that, it gives me one more thread to manage and terminate correctly. Is there any better way to do this?</p>