Wednesday, June 11, 2008

How to run external system commands in Java

Running a system command is relatively simple - once you've seen it done the first time. It involves the use of two Java classes, the Runtime class and the Process class. Basically, you use the exec() method of the Runtime class to run the command as a separate process. This returns a Process object for managing the subprocess. Then you use the getInputStream() and getErrorStream() methods of the Process object to read the normal output of the command, and the error output of the command. What you do with the output of the command executed is entirely up to you and the application you're creating.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//demonstrate  to check how many process are running.

public class RunCommand
{
  public static void main(String args[])
  {

    String s = null;

    try
    {

      // run the Unix "ps -ef" command
      // run "tasklist /svc" or "tasklist" command on windowns

      Process p = Runtime.getRuntime().exec("tasklist");
//      p.waitFor();

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

      // read the output from the command

      System.out.println("Here is the standard output of the command:\n");
      int count = 0;
      while ((s = stdInput.readLine()) != null)
      {
        System.out.println(s);
        count++;
      }
      System.out.println("total process:" + (count - 2));
      
      // read any errors from the attempted command

      System.out.println("Here is the standard error of the command (if any):\n");
      while ((s = stdError.readLine()) != null)
      {
        System.out.println(s);
      }

      System.exit(0);
    } catch (Exception e)
    {
      System.out.println("exception happened - here's what I know: ");
      e.printStackTrace();
      System.exit(-1);
    }
  }

}
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory