我在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.
答案 0 :(得分:13)
您需要使用waitFor()
代替wait()
。这样你的线程就会阻塞,直到执行的命令完成。
答案 1 :(得分:6)
我在这里找到了答案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();
}
}
答案 2 :(得分:3)
这应该有效。如果没有,请指定什么不起作用
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