tags:

views:

217

answers:

3

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.

A: 

I read that Windows uses NUL, but don't count on it, I've never tried it.

Pepijn
+3  A: 

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.

BalusC
NUL does not work on Unix. It is a DOS remniscense.
Thorbjørn Ravn Andersen
Thank you for confirmation. Didn't have a nix platform right at hand to test :)
BalusC
@BalusC: mind if I edit to keep only the Commons IO suggestion?
bmargulies
I edited to push the `NullOutputStream` more. Is it OK so? On the other hand, you're free to edit it :)
BalusC
ln -s /dev/null NUL
edgar.holleis
+5  A: 

You can use NullOutputStream from apache commons http://commons.apache.org/io/apidocs/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
    }
}
iseletsk
(The Null Object Pattern, a special case of the Special Case Pattern.) (I'd add an override (with @Override) of `write(int,int,byte[])` for added (although probably irrelevant) performance. I've always used a single instance for the null object, but I guess you might get external locking issues (`Reader`/`Writer`s have a problem with decorators here).) (This comment contains a deliberate mistake.)
Tom Hawtin - tackline
Good point about `@Override`, which would catch the deliberate mistake.
trashgod