In Java, how can I redirect System.out to null then back to stdout again?

Man, this is not so good, because Java is cross-platform and ‘/dev/null’ is Unix specific (apparently there is an alternative on Windows, read the comments). So your best option is to create a custom OutputStream to disable output.

try {
    System.out.println("this should go to stdout");

    PrintStream original = System.out;
    System.setOut(new PrintStream(new OutputStream() {
                public void write(int b) {
                    //DO NOTHING
                }
            }));
    System.out.println("this should go to /dev/null, but it doesn't because it's not supported on other platforms");

    System.setOut(original);
    System.out.println("this should go to stdout");
}
catch (Exception e) {
    e.printStackTrace();
}

Leave a Comment