来自 Java 的慢速系统命令

Slow System Commands From Java

我正在从 Java 调用 bash 脚本。 该脚本执行以下操作:

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() 永远等待。

进程的 Javadoc class:

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.