How to execute system commands (linux/bsd) using Java

What you are doing looks fine. If your command is only returning a single string, you don't need the while loop, just store the reader.readLine() value in a single String variable.

Also, you probably should do something with those exceptions, rather than just swallowing them.


That is the best way to do it. Also you can use the ProcessBuilder which has a variable argument constructor, so you could save a line or two of code


Your way isn't far off from what I'd probably do:

Runtime r = Runtime.getRuntime();
Process p = r.exec("uname -a");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";

while ((line = b.readLine()) != null) {
  System.out.println(line);
}

b.close();

Handle whichever exceptions you care to, of course.