17

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.

bmargulies
  • 97,814
  • 39
  • 186
  • 310

4 Answers4

20

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
    }
}
tar
  • 1,538
  • 1
  • 20
  • 33
iseletsk
  • 477
  • 3
  • 9
  • 3
    (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 Jan 24 '10 at 19:43
  • Good point about `@Override`, which would catch the deliberate mistake. – trashgod Jan 24 '10 at 21:21
  • I'd want to override all the "write()" methods. I guess the JVM might be smart enough to figure out that a looped write of an array is still a no-op and treat those as no-ops, too, but I hate to depend on JVM runtime optimizations. – Thomas Andrews Aug 15 '12 at 18:47
4

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
  • 1,082,665
  • 372
  • 3,610
  • 3,555
4

Starting from JDK 11, you can use a new static method on OutputStream - nullOutputStream.

var out = OutputStream.nullOutputStream();
SerCe
  • 5,826
  • 2
  • 32
  • 53
0

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).