I've tried to temporarily redirect System.out to /dev/null using the following code but it doesn't work.
System.out.println("this should go to stdout");
PrintStream original = System.out;
System.setOut(new PrintStream(new FileOutputStream("/dev/null")));
System.out.println("this should go to /dev/null");
System.setOut(original);
System.out.println("this should go to stdout"); // This is not getting printed!!!
Anyone have any ideas?
In Unix, how do I redirect error messages to /dev/null? You can send output to /dev/null, by using command >/dev/null syntax.
If you create a PrintStream connected to a ByteArrayOutputStream , then you can capture the output as a String . Example: // Create a stream to hold the output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); // IMPORTANT: Save the old System. out!
/dev/null in Linux is a null device file. This will discard anything written to it, and will return EOF on reading. This is a command-line hack that acts as a vacuum, that sucks anything thrown to it.
Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.
Man, this is not so good, because Java is cross-platform and '/dev/null' is Unix specific (apparently there is an alternative on Windows, read the comments). So your best option is to create a custom OutputStream to disable output.
try { System.out.println("this should go to stdout"); PrintStream original = System.out; System.setOut(new PrintStream(new OutputStream() { public void write(int b) { //DO NOTHING } })); System.out.println("this should go to /dev/null, but it doesn't because it's not supported on other platforms"); System.setOut(original); System.out.println("this should go to stdout"); } catch (Exception e) { e.printStackTrace(); }
You can use the class NullPrintStream below as:
PrintStream original = System.out; System.setOut(new NullPrintStream()); System.out.println("Message not shown."); System.setOut(original);
And the class NullPrintStream is...
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class NullPrintStream extends PrintStream { public NullPrintStream() { super(new NullByteArrayOutputStream()); } private static class NullByteArrayOutputStream extends ByteArrayOutputStream { @Override public void write(int b) { // do nothing } @Override public void write(byte[] b, int off, int len) { // do nothing } @Override public void writeTo(OutputStream out) throws IOException { // do nothing } } }
Since JDK 11 there is OutputStream.nullOutputStream()
. It does exactly what you are looking for:
System.setOut(new PrintStream(OutputStream.nullOutputStream());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With