title: Control a command line program session via Java
body: <p>I have a computer algebra program (called Reduce) that works in the shell in an interactive manner: launch Reduce in the shell, then you can define variables, compute this and that, and what not. Reduce prints the output into the shell. My idea is that I want to build a frontend for this text-based program that evaluates its output and converts it into a nice LaTeX style formula. For this I want to use Java.</p>
  
  <p>I can start Reduce via exec(). But how can I emulate text input to the opened shell, and how can I read back what Reduce writes into the shell?</p>
  
  <p>Thanks
  Jens</p>
  
  <p>Edit 1: Current Code</p>
  
  <pre><code>// get the shell
  Runtime rt = Runtime.getRuntime();
  
  // execute reduce
  String[] commands = {"D:/Programme/Reduce/reduce.com", "", ""};
  Process proc = null;
  try {
      proc = rt.exec(commands);
  } catch (Exception e) {
      System.out.println("Error!\n");
  }
  
  // get the associated input / output / error streams
  BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
  BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
  
  // read the output from the command
  System.out.println("Here is the standard output of the command:\n");
  String s = null;
  try {
      while ((s = stdInput.readLine()) != null) {
          System.out.println(s);
      }
  } catch (Exception e) {
  }
  
  // read any errors from the attempted command
  System.out.println("Here is the standard error of the command (if any):\n");
  try {
      while ((s = stdError.readLine()) != null) {
          System.out.println(s);
      }
  } catch (Exception e) {
  }
  </code></pre>