Friday, August 20, 2010

Java : Simple program to Run System Commands

Many times we require to execute system command using java program. Java do support to this using Process class, we can execute command on Runtime object using exec("command") method.

Eg : Process p = Runtime.getRuntime().exec(command);

Lets see a simple java program to run system command. directly you can this program and see the output


/* RunSystemCommand.java */

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

public class RunSystemCommand {

    public void runCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";

            System.out.println("Output stream :: \n");
            // reading output stream of the command
            while ((s = inputStream.readLine()) != null) {
                System.out.println(s);
            }
           
            // reading any errors of the command
            System.out.println("Error stream (if any) :: \n");
            while ((s = errorStream.readLine()) != null) {
                System.out.println(s);
            }
           
        } catch (Exception e) {
           
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
       
        RunSystemCommand obj = new RunSystemCommand();
       
        //Example system commands
        //obj.runCommand("cmd /c copy c:\\java\\Test.java d:\\data");
        //obj.runCommand("javac");   
       
        obj.runCommand("cmd /c dir");

    }

}


Output


No comments:

Post a Comment