Search code examples
javaprocessiostreamjava-io

Reading error stream from a process


I am writing a java program to read the error stream from a process . Below is the structure of my code --

ProcessBuilder probuilder = new ProcessBuilder( command );              
Process process = probuilder.start(); 
InputStream error = process.getErrorStream();
InputStreamReader isrerror = new InputStreamReader(error);
BufferedReader bre = new BufferedReader(isrerror);
while ((linee = bre.readLine()) != null) {
        System.out.println(linee);
    }

The above code works fine if anything is actually written to the error stream of the invoked process. However, if anything is not written to the error stream, then the call to readLine actually hangs indefinitely. However, I want to make my code generic so that it works for all scenarios. How can I modify my code to achieve the same.

Regards, Dev


Solution

  • This is a late reply, but the issue hasn't really solved and it's on the first page for some searches. I had the same issue, and BufferedReader.ready() would still set up a situation where it would lock.

    The following workaround will not work if you need to get a persistent stream. However, if you're just running a program and waiting for it to close, this should be fine.

    The workaround I'm using is to call ProcessBuilder.redirectError(File). Then I'd read the file and use that to present the error stream to the user. It worked fine, didn't lock. I did call Process.destroyForcibly() after Process.waitFor() but this is likely unnecessary.

    Some pseudocode below:

    
        File thisFile = new File("somefile.ext");
        ProcessBuilder pb = new ProcessBuilder(yourStringList);
        pb.redirectError(thisFile);
        Process p = pb.start();
        p.waitFor();
        p.destroyForcibly();
        ArrayList fileContents = getFileContents(thisFile);
    
    

    I hope this helps with at least some of your use cases.