"Turn off" the output stream

Oak picture Oak · Nov 25, 2010 · Viewed 7.6k times · Source

I'm using a wayward library that, unfortunately, prints information to System.out (or occasionally System.err). What's the simplest way to prevent this?

I've been thinking about creating an output stream to memory, replace System.out and err before every call to one of the troublemaking methods, restore them later, and just ignore the buffer of the created stream. Is there an easier, more elegant way?

EDIT: I don't want to redirect all output - that's easily accomplished. I only want to ignore output potentially generated by certain library calls.

Answer

Oak picture Oak · Nov 28, 2010

I ended up doing something like:

PrintStream out = System.out;
System.setOut(new PrintStream(new OutputStream() {
    @Override public void write(int b) throws IOException {}
}));
try {
    <library call>
} finally {
    System.setOut(out);
}

Thanks to AlexR and stacker for redirecting me to this short solution.