Java: wait for the exec process to complete before it completes

I am running a java program on Windows that collects a log from Windows events. A .csv file is created on which certain operations must be performed.

Commands are executed and transmitted through channels. How can I make my Java program wait for the process to complete?

Here is the code snippet I'm using:

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. 
+8
java process exec
source share
3 answers

You need to use waitFor() instead of wait() . This way, your thread will block until the command completes.

+12
source share

I found the answer here Run the 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(); } } 
+5
source share

That will work. If not, indicate WHAT does not work.

 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 
+1
source share

All Articles