花费时间 java_Java程序执行命令要花费很长时间

我已经阅读了许多示例,并最终使用以下代码从Java程序内部执行了命令行命令.

public static void executeCommand(final String command) throws IOException,

InterruptedException {

System.out.println("Executing command " + command);

final Runtime r = Runtime.getRuntime();

final Process p = r.exec(command);

System.out.println("waiting for the process");

p.waitFor();

System.out.println("waiting done");

try (final BufferedReader b = new BufferedReader(new InputStreamReader(

p.getInputStream()))) {

String line;

while ((line = b.readLine()) != null) {

System.out.println(line);

}

}

}

我已经用一个简单的ls命令测试了它,并且工作正常.当我尝试运行另一个命令时,它将永远耗费时间(保持运行25分钟,但尚未停止).

当我在命令行上执行tabix命令时,我得到以下统计信息

4.173u 0.012s 0:04.22 99.0% 0+0k 0+0io 0pf+0w

因此,它应该很快完成.

该命令是

time tabix file pos1 pos2 … pos190 > /dev/null

问题可能是tabix命令包含> / dev / null结尾?如果没有,什么原因可能导致此问题?

解决方法:

您需要先将阅读器附加到该流程,然后再调用它的waitFor.没有它,它可能会填满分配的输出缓冲区,然后阻塞-但仅对于大输出,小(例如测试)输出似乎很好.

public static void executeCommand(final String command) throws IOException, InterruptedException {

System.out.println("Executing command " + command);

// Make me a Runtime.

final Runtime r = Runtime.getRuntime();

// Start the command process.

final Process p = r.exec(command);

// Pipe it's output to System.out.

try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()))) {

String line;

while ((line = b.readLine()) != null) {

System.out.println(line);

}

}

// Do this AFTER you've piped all the output from the process to System.out

System.out.println("waiting for the process");

p.waitFor();

System.out.println("waiting done");

}

标签:java,optimization,command-line

来源: https://codeday.me/bug/20191011/1892074.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值