10

我在 Windows 中运行一个从 Windows 事件收集日志的 java 程序。将创建一个 .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.
4

3 回答 3

14

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

于 2012-09-16T17:07:57.653 回答
7

我在这里找到了答案Run shell script from Java Synchronously

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();
    }
}
于 2015-07-18T18:18:00.093 回答
3

这将起作用。如果没有,请指定 WHAT 到底是什么不起作用

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 +"\"");
    powershell.waitFor();
} catch (IOException e) { }
// remaining code
于 2012-09-16T17:18:27.243 回答