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

/* */


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) {
            // reading any errors of the command
            System.out.println("Error stream (if any) :: \n");
            while ((s = errorStream.readLine()) != null) {
        } catch (Exception e) {

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