Platform-independent way to discard out/err with ProcessBuilder

367 views Asked by At

On Unix you can discard a process' output with:

pb.redirectOutput(new File("/dev/null"));

While on Windows you instead need to use NUL. Is there a better option than the following snippet for supporting arbitrary platforms?

File devNull = new File("/dev/null");
if (devNull.exists()) {
  pb.redirectOutput(devNull);
} else {
  pb.redirectOutput(new File("NUL"));
}

This seems kludgy, but there isn't a ProcessBuilder.Redirect.NULL field to use or seemingly any other way to do this in the API.

I'm also a little concerned that this doesn't handle the non-Unix-non-Windows case (but I'm not sure if such a case exists).

I'm aware of platform-independent /dev/null output sink for Java and similar questions, however using a no-op OutputStream still requires spinning up a thread to actively discard the output - I'd prefer to let the OS do it for me.

1

There are 1 answers

0
dimo414 On BEST ANSWER

Judging from the behavior of Python's subprocess module the code snippet in the question is likely sufficient. subprocess.DEVNULL uses os.devnull, which in turn comes from os.path which is defined in either ntpath (as nul) or posixpath (as /dev/null).

These appear to be the only paths Python supports, so similarly using either nul or /dev/null as appropriate should be sufficient in Java. There may be a more elegant, platform independent option for Java, but if so I haven't found it.