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

发布于 2021-01-29 20:25:08

我已经阅读了许多示例,并最终使用以下代码从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

因此,它应该很快完成。

该命令是

时间标签文件pos1 pos2 … pos190> / dev / null

问题可能是tabix命令包含> /dev/null在末尾吗?如果不是,什么原因可能导致此问题?

关注者
0
被浏览
84
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要 先将 阅读器附加到该流程上, 然后才能 调用它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");
    }
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看