In Java, how can I redirect System.out to null the

2019-01-22 11:19发布

问题:

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?

回答1:

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();
}


回答2:

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
    }

  }

}


回答3:

Old question, I know, but would this small line do the trick on Windows?

System.setOut(new PrintStream(new File("NUL")));

Much less code and looks pretty direct to me.



回答4:

I think System.setOut(null); should work too. At least it worked for me.