How to execute Microsft windows's shell command using/in Java?

UPDATED: 19 February 2011
Interacting with shell is essential in certain situation. Lets see how you can execute single command using Java program.

public class cmd {
    public static void main(String[] args) {
       try {
                String[] command = new String[3];
                command[0] = "cmd";
                command[1] = "/c";
                command[2] = "msg * www.javaquery.com";

                Process p = Runtime.getRuntime().exec(command);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String Error;

                while ((Error = stdError.readLine()) != null) {
                    System.out.println(Error);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }       
    }
}
This is how you can use the java to execute the Shell command. To execute your command change the value in command[2] this will executed in shell and give the output.

Related articles:

2 comments :