我试图便宜一些,并uname -a在Java中执行本地系统命令()。我想从中获取输出uname并将其存储在String中。最好的方法是什么?当前代码:
uname -a
uname
public class lame { public static void main(String args[]) { try { Process p = Runtime.getRuntime().exec("uname -a"); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line=reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } } catch(IOException e1) {} catch(InterruptedException e2) {} System.out.println("finished."); } }
你的方法与我可能要做的事情并不遥远:
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();
当然,请处理你关心的任何异常情况。