在Java中,如何将System.out重定向到null,然后再次返回到stdout?

2022-09-01 06:34:32

我试图使用以下代码暂时将System.out重定向到/dev/null,但它不起作用。

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!!!

有人有什么想法吗?


答案 1

伙计,这不是那么好,因为Java是跨平台的,而'/dev/null'是Unix特定的(显然Windows上有另一种选择,请阅读评论)。因此,您最好的选择是创建自定义输出流以禁用输出。

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

您可以使用下面的类 NullPrintStream 作为:

PrintStream original = System.out;
System.setOut(new NullPrintStream());
System.out.println("Message not shown.");
System.setOut(original);

类 NullPrintStream 是...

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
    }

  }

}

推荐