Execute CommandLine Inside Java


Here is the code how to execute command line like ping, netstat etc from java application


/**
* com.harry.latihan.system
* ExecuteCommandPrompt.java
* Jun 4, 2007 - 12:58:06 PM
*/
package com.harry.latihan.system;

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

/**
* @author Harry Christian
* @email harry.christian@yahoo.com
*
*/
public class ExecuteCommandPrompt
{

   public static void main(String[] args)
  {
      String command = "ping www.google.com -t";
      String message = null;
      try
     {
         Process p = Runtime.getRuntime().exec(command);
         BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // Read the output from command
       while ((message = input.readLine()) != null)
              System.out.println(message);
        // Read any errors from command
        while ((message = error.readLine()) != null)
              System.out.println(message);
        System.exit(0);
    } catch (IOException e)
    {
        e.printStackTrace();
       System.exit(-1);
    }
  }
}