Executing Shell Command From Java Program


Shell commands can be executed from within Java programs by using exec() method of Runtime class.

See example below:
try {
    Process process = Runtime.getRuntime().exec("your-command");
} catch (IOException e) {
    e.printStackTrace();
}

Output of the executed command can also be read as
Process proc = Runtime.getRuntime().exec("your-command");


BufferedReader stdInput = new BufferedReader(new

     InputStreamReader(proc.getInputStream()));


BufferedReader stdError = new BufferedReader(new

     InputStreamReader(proc.getErrorStream()));


System.out.println("Standard Output:\n");

String s = null;

while ((s = stdInput.readLine()) != null) {

    System.out.println(s);

}

System.out.println("Standard Error:\n");

while ((s = stdError.readLine()) != null) {

    System.out.println(s);

}

0 comments:

Post a Comment