20

Is there a way to set the stream System.err so everything written to it is ignored? (i.e. discarded not outputted)

skaffman
  • 390,936
  • 96
  • 800
  • 764
dtech
  • 13,092
  • 11
  • 44
  • 71

4 Answers4

40
System.setErr(new PrintStream(new OutputStream() {
    public void write(int b) {
    }
}));
dogbane
  • 254,755
  • 72
  • 386
  • 405
  • 7
    I have found another way: System.err.close(); – elou Aug 02 '12 at 14:47
  • @elou Do you know how to restore the original System.err after you've closed it? – Noumenon Jul 05 '18 at 18:35
  • 1
    Hi @Noumenon, I have investigate the question and came to the same conclusion as here: [It is not possible to reopen](https://stackoverflow.com/a/27286893/281188). If you need to reopen, you should prefer to backup the stream with `PrintStream _err = System.err;` before overwriting with `System.setErr(..)`. After that it's possible to restore with `System.setErr(_err)`. Regards, Éric. – elou Jul 10 '18 at 07:43
18

You can use System.setErr() to give it a PrintStream which doesn't do anything.

See @dogbane's example for the code.

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
4

Just set Error to dommy implementation:

System.setErr(new PrintStream(new OutputStream() {
            @Override
            public void write(int arg0) throws IOException {
                // keep empty
            }
        }));

You need to have special permission to do that.

RuntimePermission("setIO")
Hurda
  • 4,577
  • 8
  • 33
  • 49
2

You could redirect the err Stream to /dev/null

OutputStream output = new FileOutputStream("/dev/null");
PrintStream nullOut = new PrintStream(output);
System.setErr(nullOut);
cb0
  • 8,039
  • 9
  • 54
  • 78