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");
}
上一篇:jQuery / Javascript框架效率


下一篇:优化PHP字符串连接