20

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
dtech
  • 13,741
  • 11
  • 48
  • 73

5 Answers5

42
System.setErr(new PrintStream(new OutputStream() {
    public void write(int b) {
    }
}));
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 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
  • 2
    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
  • 525,659
  • 79
  • 751
  • 1,130
5

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,647
  • 8
  • 35
  • 49
1

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,415
  • 9
  • 52
  • 80
0

Using commons-io's NullOutputStream, just:

System.setErr(new PrintStream(new NullOutputStream()));
Daniel Hári
  • 7,254
  • 5
  • 39
  • 54