title: Redirecting Input/Output/Error Streams of a CMD.exe Process Completely with Java
body: <p>My aim with this project was to have a remote command prompt feel with Java.  Using TCP/IP sockets, I was aiming to run a command prompt process on one computer, and virtually transmit all control to the other side.  I immediately stumbled over Runtime.getRuntime().exec() and Process objects, etc.  I've solved my problem about halfway.  With my remote command prompt, I can run a single command, gather the output, and send it back to the other side.  The problem is, I can only seem to run one command per command prompt instance.  This won't do (with situations where I need to change directory and THEN run a command, etc).  I've stripped all socket/networking programming from this situation to show you (and to create an easier testing environment for me).</p>
  
  <pre><code>import java.io.*;
  
  
  public class testingProgram {
  
   public static void main(String[] args) {
  
    Runtime rt = Runtime.getRuntime();
    StringBuilder inputMessage = new StringBuilder();
    String resultData;
    try {
  
     Process pr = rt.exec("cmd.exe /c net user");
     BufferedReader processInput = new BufferedReader(new InputStreamReader(pr.getInputStream()));
     BufferedReader errorProcessInput = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
     PrintWriter processOut = new PrintWriter(pr.getOutputStream());
     while( (resultData = processInput.readLine()) != null ) {
        inputMessage.append(resultData + "\n");
     }
     resultData = inputMessage.toString();
     System.out.print(resultData);
    } catch(IOException e) {
  
    } //catch(InterruptedException e) {
  
    //}
   }
  
  }
  </code></pre>
  
  <p>I have a lot more, but this is where my problem is.  I can customize the command "net user" with a simple variable and message from the socketstream, so that's not my problem.  My problem is that I need to create an ongoing command prompt instance, retaining all redirections of the input/output.  Basically, I would like to be able to send another command AFTER "net user".  </p>
  
  <p>I have gathered and redirected the output stream.  I want to be able to do something like:</p>
  
  <pre><code>processOut.write("net user");
  </code></pre>
  
  <p>I want to be able to use this, have the command prompt run the command, and retain the output (whether it be from the errorStream OR the inputStream).  </p>
  
  <p>I just need some more direction on how to go about doing this.  </p>