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