Skip to content
Advertisement

platform-independent /dev/null output sink for Java

Other than an anonymous class (new OutputStream() { ... }), can anyone suggest a moral equivalent of new FileOutputStream("/dev/null") that also works on Windows?

In case someone’s wondering ‘what’s this for?’

I have a program that does a consistency analysis on a file. It has a ‘verbose’ option. When the verbose option is on, I want to see a lot of output. The program is not in a hurry, it’s a tool, so instead of writing all those extra if statements to test if I want the output, I just want to write it to the bit-bucket when not desired.

Advertisement

Answer

You can use NullOutputStream from apache commons https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/output/NullOutputStream.html

Or just implement your own

package mypackage;

import java.io.OutputStream;
import java.io.IOException;

public class NullOutputStream extends OutputStream {
    public void write(int i) throws IOException {
        //do nothing
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement