Blocking or redirecting standard output error

suggest change

Sometimes a poorly designed 3rd-party library will write unwanted diagnostics to System.out or 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 Unix, Linux, or macOS, the shell can do it with > 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 redirects standard output and standard error to /dev/null, which discards anything written to those streams. The second 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 redirect the streams inside a Java application with System.setOut() and System.setErr(). For example, this sends standard output and standard error to two log files:

System.setOut(new PrintStream(new FileOutputStream(new File("out.log"))));
System.setErr(new PrintStream(new FileOutputStream(new File("err.log"))));

A new FileDescriptor() is invalid, so writing to it throws IOException. That is not the same as /dev/null. Discard output with an OutputStream whose write methods do nothing (Java 11 adds OutputStream.nullOutputStream()), or open the platform’s null device.

Caution: be careful how you use setOut and setErr:

  1. The redirection will affect the entire JVM.
  2. By doing this, you are taking away the user’s ability to redirect the streams from the command line.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents