java执行等待时间,Java程序执行命令需要很长时间

I have read many examples and ended up using the following code to execute a command line command from inside of a Java program.

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

}

}

}

I have tested it with a simple ls command and it works fine. When I try to run another command, it is taking forever (kept running for 25 minutes and did not stop yet).

When I execute a tabix command on the command line, I get the following statistics

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

Hence it should finish fast.

The command is

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

Could the problem be that the tabix command includes > /dev/null at the end? If not, what could cause this issue?

解决方案

You need to attach the reader to the process before calling it's waitFor. Without that it could fill it's allocated output buffer and then block - but only for big output, small (e.g. test) output will seem to be fine.

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");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值