This snippets demonstrates how to execute shell command (navtive to OS) and captures its output as if it was running from the command line. Once the command is executed, it waits for it, and captures any output produced by the command and dumps it to the screen.
Remember this piece of code has to be executed from a Unix/Linux shell, or cygwin or dos shell in order for this to work.
package com.livrona.snippets.system;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* This snippet shows how to execute the a shell command
* and get the output of the program response.
*
* @author mvohra
*/
publicclass ExecuteShellCommand {
/**
* Main
* @param args
* @throws Exception
*/
publicstaticfinalvoid main(String args[]) throws Exception {
// example of the command, it can be windows/unix/linux etc.
// list of the contents of the directory sorted by time
String cmd ="ls -lt";
// get the handle to runtime environment
Runtime run = Runtime.getRuntime();
// execute the command, which creates a new process
Process pr = run.exec(cmd);
// wait for the process to finish
pr.waitFor();
// get the input stream of the process
BufferedReader buf =new BufferedReader(new InputStreamReader(pr
.getInputStream()));
String line ="";
// read the output of the stream line by line and print
while ((line = buf.readLine()) !=null) {
// print it or store the output
System.out.println(line);
}
}
}