Skip to content
Advertisement

Java ProcessBuilder: How to suppress output instead of redirecting it

I’m using a ProcessBuilder to execute commands and redirect the output. I now want to add the possibility to have no output at all.

Of course I could redirect into a file, but this would leave unnecessary files on the users system.

I am looking for a solution that

  • works on all platforms, including Windows (e.g. not redirecting to /dev/null)
  • does not misuse try-catch (e.g. redirecting to null and ignore the exception)

The only way I could find was this:

ProcessBuilder processBuilder = new ProcessBuilder(command);
if (suppressOutput) {
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
}

But that prints to the underlying shell, which is not literally “no output”.

Here is my use of processBuilder with output not surpressed:

ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File(workingdir));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();

while (process.isAlive()) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) { }
    // check for termination request
    if (terminationRequest()) {
        process.destroy();
        return -1;
    }
}
return process.exitValue();

Advertisement

Answer

The DISCARD redirect option has been added in Java 9. You could use that if you upgrade Java. Otherwise, you could simply replicate that behaviour because the DISCARD redirect enum uses a file instance which redirects to null device as below.

   private static File NULL_FILE = new File(
          (System.getProperty("os.name")
                     .startsWith("Windows") ? "NUL" : "/dev/null")
   );

Then you could use the overloaded redirectOutput method;

if (suppressOutput) {
   processBuilder.redirectOutput(NULL_FILE);
}

This is identical to Java 9’s behaviour.

Advertisement