A few times recently i’ve needed to capture the output from an OS specific command in Java. It’s not terribly difficult, but this little example may save you some time.
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
private final static String COMMAND = "/usr/bin/uptime";
public static void main(String[] args) throws Exception {
Process process = Runtime.getRuntime().exec(COMMAND);
BufferedReader stdout =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line=stdout.readLine())!=null) {
System.out.println(line);
}
process.waitFor(); // unlikely we'd ever wait as we've got EOF on stdout
System.out.println("Exit code = "+process.exitValue());
}
}
And here is the output as you would expect :
08:30:47 up 12 days, 23:53, 1 user, load average: 1.87, 1.99, 2.07 Exit code = 0