Get the output result of a process with java

java, processbuilder

Solution

You don't want that call to `waitFor()` since it waits until the process is destroyed. You also don't want to read for as long as the `InputStream` is open, since such a read would terminate only when the process is killed.

Instead, you can simply start the process, and then wait for 7 seconds. Once 7 seconds have passed, read the available data in the buffer without waiting for the stream to close:

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
Thread.sleep(7000); //Sleep for 7 seconds
while (stdInput.ready()) { //While there's something in the buffer
     //read & print - replace with a buffered read (into an array) if the output doesn't contain CR/LF
    System.out.println(stdInput.readLine()); 
}
p.destroy(); //The buffer is now empty, kill the process.

If the process keeps printing, so `stdInput.ready()` always returns true you can try something like this:

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[16 * 1024]; // 16 KiB buffer, change size if needed
long startedReadingAt = System.currentTimeMillis(); //When did we start reading?
while (System.currentTimeMillis() - startedReadingAt < 7000) { //While we're waiting
    if (stdInput.ready()){
        int charsRead = stdInput.read(buffer); //read into the buffer - don't use readLine() so we don't wait for a CR/LF
        System.out.println(new String(buffer, 0, charsRead));  //print the content we've read
    } else {
        Thread.sleep(100); // Wait for a while before we try again
    }
}
p.destroy(); //Kill the process

In this solution, instead of sleeping, the thread spends the next 7 seconds reading from the `InputStream`, then it closes the process.

Problem

I want to execute a process for some time and then get the output and destroy the process. This is my code ``` BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader temp; p.waitFor(7, TimeUnit.SECONDS); temp=stdInput; p.destroy(); System.out.println(temp.readLine()); ``` but I get as result ``` java.io.IOException: Stream closed ``` How can I copy the result after executing the process 7 seconds? If I use this code ``` p.waitFor(7, TimeUnit.SECONDS); while ((inputRead=stdInput.readLine()) != null){ Helper.log(inputRead); } ``` the while loop will never terminate because the process is still alive after the `waitFor`, so I have to destroy it. And If I destroy the process I am not able to get the content of `stdInput` anymore.

Original source