Blocking or redirecting standard output errorsuggest change
Sometimes a poorly designed 3rd-party library will write unwanted diagnostics to
System.err streams. The recommended solutions to this would be to either find a better library or (in the case of open source) fix the problem and contribute a patch to the developers.
If the above solutions are not feasible, then you should consider redirecting the streams.
Redirection on the command line
On a UNIX, Linux or MacOSX system can be done from the shell using
\> redirection. For example:
$ java -jar app.jar arg1 arg2 > /dev/null 2>&1 $ java -jar app.jar arg1 arg2 > out.log 2> error.log
The first one redirects standard output and standard error to “/dev/null”, which throws away anything written to those streams. The second of redirects standard output to “out.log” and standard error to “error.log”.
(For more information on redirection, refer to the documentation of the command shell you are using. Similar advice applies to Windows.)
Alternatively, you could implement the redirection in a wrapper script or batch file that launches the Java application.
Redirection within a Java application
It is also possible to redired the streams within a Java application using
System.setErr(). For example, the following snippet redirects standard output and standard error to 2 log files:
System.setOut(new PrintStream(new FileOutputStream(new File("out.log")))); System.setErr(new PrintStream(new FileOutputStream(new File("err.log"))));
If you want to throw away the output entirely, you can create an output stream that “writes” to an invalid file descriptor. This is functionally equivalent to writing to “/dev/null” on UNIX.
System.setOut(new PrintStream(new FileOutputStream(new FileDescriptor()))); System.setErr(new PrintStream(new FileOutputStream(new FileDescriptor())));
Caution: be careful how you use
- The redirection will affect the entire JVM.
- By doing this, you are taking away the user’s ability to redirect the streams from the command line.