How do i get the output of a command?

Tested this code below in Win10. Command is executed and the output of this command is piped to a text file.

Kf


import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.util.List;
import java.util.ArrayList;


//REFERENCE: https://www.tutorialspoint.com/java/lang/process_geterrorstream.htm
//REFERENCE: https://discourse.processing.org/t/how-do-i-get-the-output-of-a-command/769
//REFERENCE: http://www.codecodex.com/wiki/Execute_an_external_program_and_capture_the_output


ArrayList<String> outputBuffer = new ArrayList<String>();
Process p=null;
InputStream error=null;

try {

  String[] pars ={"cmd", "/c", "dir", "/D", ">>C:\\mySandBox\\procdemo.txt"};

  // create a new process
  System.out.println("Creating Process... [Executing 1 of 4 possible cases]");
  //p = Runtime.getRuntime().exec("notepad.exe");                                    // An example of good case GOOD 
  //p = Runtime.getRuntime().exec("nnotepad.exe");                                   // Example on ERROR: Typo in name
  //p = Runtime.getRuntime().exec("cmd /c dir /D >> C:\\mySandBox\\procdemo.txt");   //Custom cmd
  p = Runtime.getRuntime().exec(pars);   //Custom cmd                                //Same as before

  final BufferedReader
    out = new BufferedReader(new InputStreamReader(p.getInputStream())), 
    err = new BufferedReader(new InputStreamReader(p.getErrorStream()));

  outputBuffer.clear();
  String read;
  while ((read = out.readLine()) != null) outputBuffer.add(read);

  System.out.println("Size out buffer: " + outputBuffer.size());
  for (String ss : outputBuffer) {
    System.out.println("WATCH2 : " + ss);
  }

  // get the error stream of the process and print it
  error = p.getErrorStream();

  if (error.available() > 0) {
    System.out.println("ERROR DETECTED: ");
    for (int i = 0; i < error.available(); i++) {
      System.out.print( ((char) error.read()));
    }
    System.out.println();
  }

  // wait for 10 seconds and then destroy the process
  Thread.sleep(4000);
  p.destroy();
} 
catch (Exception ex) {
  ex.printStackTrace();
}
2 Likes