Eri*_*man 37 java output-redirect
我试图廉价并uname -a在Java中执行本地系统命令().我希望从中获取输出uname并将其存储在String中.这样做的最佳方式是什么?当前代码:
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*lla 61
你的方式与我可能做的不远:
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();
Run Code Online (Sandbox Code Playgroud)
当然,处理你关心的任何例外情况.
这是最好的方法.您还可以使用具有可变参数构造函数的ProcessBuilder,这样您就可以保存一行或两行代码
| 归档时间: |
|
| 查看次数: |
72514 次 |
| 最近记录: |