Java: wait for exec process till it exits

前端 未结 3 1163
傲寒
傲寒 2020-12-31 13:19

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

The commands a

相关标签:
3条回答
  • 2020-12-31 13:44

    You need to use waitFor() instead of wait(). That way your thread will block until the executed command finishes.

    0 讨论(0)
  • 2020-12-31 13:44

    This shall work. If not, specify WHAT exactly 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
    
    0 讨论(0)
  • 2020-12-31 13:57

    I found the answer here 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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题