platform-independent /dev/null output sink for Jav

2019-02-08 14:00发布

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.

标签: java stream
3条回答
老娘就宠你
2楼-- · 2019-02-08 14:31

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
    }
}
查看更多
Evening l夕情丶
3楼-- · 2019-02-08 14:35

NUL works for Windows NT, but that doesn't work in *NIX.

output = new FileOutputStream("NUL");

Better use NullOutputStream of the Commons IO instead to be platform independent.

查看更多
看我几分像从前
4楼-- · 2019-02-08 14:49

As long as you don't care about the slight performance difference (and you don't feel like you might run out of space), you can just use "/dev/null". On Windows, it will create a real file on whatever your current drive is (e.g., c:\dev\null).

查看更多
登录 后发表回答