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 +0瓦特

因此它应该快速完成。

的命令是

时间TABIX文件POS1 POS2 ... pos190>的/ dev/null的

可能问题是该TABIX命令包括> /dev/null在结束了吗?如果不是,可能会导致这个问题?

+0

什么是 “永远”?你有没有试过其他的命令,既简单又困难?根据命令中的内容,可能会有额外的延迟。 – Juru 2014-10-01 20:44:10

+2

请详细说明。什么是你正在运行的确切命令?什么是直接运行命令的时间,以及执行此命令然后终止的'public static void main'的时序是什么? – 2014-10-01 20:44:12

+0

该命令已运行14分钟并仍在运行。 – Tad 2014-10-01 20:45:26

您需要将读者附加到之前称为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"); 
}