Java程序执行一个需要很长时间的命令
我阅读了许多示例,最后使用以下代码从Java程序内部执行命令行命令Java程序执行一个需要很长时间的命令,java,optimization,command-line,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();
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
?如果不是,是什么原因导致此问题?在调用进程的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");
}
什么是“永远”?您是否尝试过其他简单和困难的命令?根据命令中的内容,可能会有额外的延迟。请提供更多详细信息。您正在运行的确切命令是什么?直接运行该命令的计时是什么?刚刚执行该命令然后终止的
公共静态void main
的计时是什么?该命令已运行14分钟,并且仍在运行。该命令基本上是时间选项卡文件pos1 pos2 pos3。。。pos190>/dev/null在调用进程的waitFor
之前,需要将读取器连接到进程。如果没有它,它将填充分配的输出缓冲区,然后阻塞-但只有对于大输出,小输出似乎是好的。谢谢,这救了我!