Removing a standard error in Java

When starting a process with Java, stderr and stdout can block the output if I do not read from pipes. I currently have a stream that is actively reading from one and the main stream blocks on another.

Is there an easy way to join two threads or otherwise make the subprocess continue without losing data in stderr?

+4
source share
2 answers

Set the redirectErrorStream property on a ProcessBuilder to send stderr output to stdout:

ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); 

Then you should create a thread to handle the process thread, something like the following:

 Process p = builder.start(); InputHandler outHandler = new InputHandler(p.getInputStream()); 

Where the InputHandler is defined as:

 private static class InputHandler extends Thread { private final InputStream is; private final ByteArrayOutputStream os; public InputHandler(InputStream input) { this.is = input; this.os = new ByteArrayOutputStream(); } public void run() { try { int c; while ((c = is.read()) != -1) { os.write(c); } } catch (Throwable t) { throw new IllegalStateException(t); } } public String getOutput() { try { os.flush(); } catch (Throwable t) { throw new IllegalStateException(t); } return os.toString(); } } 

Alternatively, just create two InputHandlers for InputStream and ErrorStream. To know that the program will be blocked, if you do not read them, this is 90% of the battle :)

+4
source

Just two threads, one reading from stdout, one from stderr?

0
source

Source: https://habr.com/ru/post/1276692/


All Articles