Java program to execute a command taking a long time

前端 未结 1 1751
青春惊慌失措
青春惊慌失措 2021-01-21 13:27

I have read many examples and ended up using the following code to execute a command line command from inside of a Java program.

public static void executeComman         


        
1条回答
  •  礼貌的吻别
    2021-01-21 14:17

    You need to attach the reader to the process before calling it's waitFor. Without that it could fill it's allocated output buffer and then block - but only for big output, small (e.g. test) output will seem to be fine.

    public static void executeCommand(final String command) throws IOException, InterruptedException {
        System.out.println("Executing command " + command);
        // Make me a Runtime.
        final Runtime r = Runtime.getRuntime();
        // Start the command process.
        final Process p = r.exec(command);
        // Pipe it's output to System.out.
        try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
    
            while ((line = b.readLine()) != null) {
                System.out.println(line);
            }
        }
        // Do this AFTER you've piped all the output from the process to System.out
        System.out.println("waiting for the process");
        p.waitFor();
        System.out.println("waiting done");
    }
    

    0 讨论(0)
提交回复
热议问题