Java程序执行一个命令需要很长时间

标签 java optimization command-line

我阅读了很多示例,最终使用以下代码从 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程序执行一个命令需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150191/

相关文章:

java - 使用共享首选项存储未提交的数据

python - 使用Python过滤tail的输出

pdf - 批量打印在文本文件中列出的 PDF 文件

java - 创建一个扩展 Spring 标签库的自定义标签库

java - java中如何让一个方法转到main方法?

optimization - 在 Enterprise Architect 中批量导入 XMI 的有效方法

java - OptaPlanner 具有链式变量的多个实体类

arrays - 重新排序两个数组的最佳算法,将公共(public)元素放在首位

git - `git` 和 `less` 集成在 OS X 终端 : prevent writing output of `less` to tty

java - Gradle 编译依赖未添加到类路径