我正在从 Java 调用 bash script 脚本。 该脚本执行以下操作:
cat /home/user/Downloads/bigtextfile.txt | grep 'hello'
在 150MB 的文本文件上运行命令行时,此特定命令大约需要 1 秒才能完成。
当使用以下调用通过 Java 调用 bash 脚本时:
command = "sh /home/user/bashfiletocall"
p = Runtime.getRuntime().exec(command);
完成的时间太长了,我等不及了。
我做错了什么吗?如果不是,你能解释一下性能大幅下降的原因吗?
注意:我在 Netbeans 中运行它,这似乎是问题所在..当我运行文件命令行时,速度很快。在 netbeans 中执行和在命令行中执行之间的性能是巨大的。
非常感谢。
private String executeCommand(String command) {
StringBuilder output = new StringBuilder();
BufferedReader reader = null;
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
最佳答案
启动进程后,您需要开始从输入流读取。否则,缓冲区将满,p.waitFor()
将永远等待。
Process 类的 Javadoc:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
关于java - 来自 Java 的系统命令速度较慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726436/