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.
Judging from the behavior of Python's
subprocess
module the code snippet in the question is likely sufficient.subprocess.DEVNULL
usesos.devnull
, which in turn comes fromos.path
which is defined in eitherntpath
(asnul
) orposixpath
(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.