要从我的intelliJ运行终端,我编写了下一个代码:
public static String runTerminalCommand (String command){
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
try {
while((line = reader.readLine()) != null) {
out.print(line + "\n");
return line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
如果有办法简化这个:)
答案 0 :(得分:1)
我首先会在这里查看正确性;那一行:
return line;
看起来很可疑。或者,更准确地说:您确定您的命令将始终打印一个行吗?因为你在读完第一行后回来了;因此省略任何其他输出。
此外:您应该更改代码以使用try-with资源 - 您的return语句只会让您的读者不公开。可能这里不是问题,因为当过程对象消失时,所有这些都应该消失,但仍然是:不好的做法。 "清理东西"在退出你的方法之前!
回答实际问题:在研究了我指出的这些概念性事物之后,你还有很多其他的事情可做。可能使用ProcessBuilder而不是某种方式"过时" Runtime.exec()调用。