[英]Java program to execute a command taking a long time
我已經閱讀了許多示例,並最終使用以下代碼從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
嗎? 如果沒有,什么原因可能導致此問題?
您需要先將閱讀器附加到該流程, 然后再調用它的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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.