In Java, how can I redirect System.out to null then back to stdout again?

北战南征 提交于 2019-12-17 15:46:47

问题


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:


Since JDK 11 there is OutputStream.nullOutputStream(). It does exactly what you are looking for:

System.setOut(new PrintStream(OutputStream.nullOutputStream());



回答5:


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



来源:https://stackoverflow.com/questions/4799006/in-java-how-can-i-redirect-system-out-to-null-then-back-to-stdout-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!