Java 有没有一种方法可以简化我编写的这个终端类,或者使它更高效:)thnks
要从intelliJ运行终端,我编写了下一个代码:Java 有没有一种方法可以简化我编写的这个终端类,或者使它更高效:)thnks,java,terminal,Java,Terminal,要从intelliJ运行终端,我编写了下一个代码: public static String runTerminalCommand (String command){ Process proc = null; try { proc = Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace();
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;
}
如果有一种方法可以简化这一点:)我将首先研究正确性;那一行:
return line;
看起来可疑。或者,更准确地说:您是否确定您的命令总是准确地打印一行?因为你是在读完第一行之后回来的;从而省略了任何其他输出
此外:您应该将代码改为使用try with resources-您的return语句只会让您的读者无法关闭。这里可能不是问题,因为当流程对象消失时,所有这些都应该消失,但仍然是:糟糕的实践。在退出你的方法之前“清理东西”
回答实际问题:在研究了我所指出的这些概念性的东西之后,你没有什么其他的办法了。可能使用ProcessBuilder而不是某种程度上“过时”的Runtime.exec()调用。您应该在一件事上问这个问题-您没有关闭读卡器,这可能会导致内存泄漏(即使对象被垃圾收集,底层资源也不会被关闭)。对于Java7和更高版本,请参阅参考资料try:我投票将这个问题作为离题题来结束,因为它属于CodeReview.SE