Java:等待exec进程直到它退出

use*_*171 9 java process exec

我在Windows中运行一个java程序,用于从Windows事件中收集日志.创建.csv文件,在该文件上执行某些操作.

命令被执行和管道.如何让我的Java程序等到进程完成?

这是我正在使用的代码片段:

Runtime commandPrompt = Runtime.getRuntime();
try {           
    Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable @{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 ';  ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
//I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked
} catch (IOException e) { }
// Remaining code should get executed only after above is completed.
Run Code Online (Sandbox Code Playgroud)

dan*_*dan 13

你需要使用waitFor()而不是wait().这样你的线程就会阻塞,直到执行的命令完成.


小智 6

我在这里找到答案从Java Synchronously运行shell脚本

public static void executeScript(String script) {
    try {
        ProcessBuilder pb = new ProcessBuilder(script);
        Process p = pb.start(); // Start the process.
        p.waitFor(); // Wait for the process to finish.
        System.out.println("Script executed successfully");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)