慢行系统命令从Java [英] Slow System Commands From Java

查看:171
本文介绍了慢行系统命令从Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Java调用一个bash脚本纸条。
该脚本执行以下操作:

 猫/home/user/Downloads/bigtextfile.txt | grep的'你好'

在运行命令行约1秒这个特殊的命令来完成的文本文件,它是150MB。

在使用下面的调用调用通过Java bash脚本:

 命令=SH / home / user中/ bashfiletocall
P =调用Runtime.getRuntime()EXEC(命令);

要完成的时间需要很长时间,我不等待。

我做得非常错误的,如果没有你可以解释为庞大的缺乏表现的原因吗?

请注意:我在Netbeans的运行它,这似乎是问题..当我跑了文件的命令行是快。在NetBeans执行和命令行之间的性能是巨大的。

非常感谢。

 私人字符串executeCommand(字符串命令){
    StringBuilder的输出=新的StringBuilder();
    读者的BufferedReader = NULL;
    进程p;
   尝试{
    P =调用Runtime.getRuntime()EXEC(命令);
    p.waitFor();  读者=新的BufferedReader(新的InputStreamReader(p.getInputStream()));    串线=;
    而((行= reader.readLine())!= NULL){
        output.append(行+\\ n);
    }}赶上(例外五){
    e.printStackTrace();
}
返回output.toString();
}


解决方案

在开始你的进程你需要开始从输入流中读取后。否则,缓冲区全速运行和 p.waitFor()将永远等待。

Process类的Javadoc:


  

由于一些本地平台只提供标准输入和输出流有限的缓冲区大小,未能及时写输入流或读取子进程的输出流可能导致子进程阻塞,甚至死锁。


I am calling a bash scrip script from Java. The script does the following:

cat /home/user/Downloads/bigtextfile.txt | grep 'hello'

This particular command when run command line takes about 1 second to complete on the text file which is 150MB.

When calling the bash script via Java using the following call:

command = "sh /home/user/bashfiletocall"
p = Runtime.getRuntime().exec(command);

The time to complete takes so long I don't wait.

Am I doing something very wrong and if not can you explain the reason for the huge lack in performance?

NOTE: I was running it in Netbeans and this seems to be the problem .. when I ran the file command line it was quick. The performance between execution in netbeans and command line is huge.

Many thanks.

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();
}

解决方案

After starting your process you need start reading from the input stream. Otherwise the buffers are running full and p.waitFor() waits forever.

Javadoc of the Process 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.

这篇关于慢行系统命令从Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆