Is there a way to set the stream System.err so everything written to it is ignored? (i.e. discarded not outputted)
Asked
Active
Viewed 7,679 times
5 Answers
42
System.setErr(new PrintStream(new OutputStream() {
public void write(int b) {
}
}));

dogbane
- 266,786
- 75
- 396
- 414
-
7I 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
-
2Hi @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
-
1
-
2
-
/dev/null doesn't exist in windows (you can use NUL on those though) – ratchet freak May 09 '11 at 12:09
-
2@rachet freak, If you have a directory called `dev` it soon will. ;) (`dev` is short for development on my PC) – Peter Lawrey May 09 '11 at 12:13
-
FileOutputStream is an overkill for this, you can use common-io NullOutputStream() – Daniel Hári May 22 '23 at 10:45
0
Using commons-io's NullOutputStream, just:
System.setErr(new PrintStream(new NullOutputStream()));

Daniel Hári
- 7,254
- 5
- 39
- 54