在Java中,如何将System.out重定向到null,然后再次返回到stdout?
我尝试使用以下代码将System.out临时重定向到/dev/null,但没有成功在Java中,如何将System.out重定向到null,然后再次返回到stdout?,java,stdout,iostream,Java,Stdout,Iostream,我尝试使用以下代码将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"); Syste
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!!!
有人有什么想法吗?伙计,这不太好,因为Java是跨平台的,“/dev/null”是特定于Unix的(显然Windows上有其他选择,请阅读评论)。因此,您最好的选择是创建一个自定义OutputStream来禁用输出
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();
}
您可以将下面的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
}
}
}
老问题,我知道,但这条小线会在Windows上起作用吗
System.setOut(新打印流(新文件(“NUL”))代码>
代码更少,对我来说非常直接。我认为System.setOut(null);应该也行。至少它对我有用。因为JDK 11已经存在了。它正是您想要的:
System.setOut(新的PrintStream(OutputStream.nullOutputStream());
我在我的系统上看到这两行代码都很好。我正在使用Java 6 update 22.BTW:小心像这样操纵system.out,而没有更广泛的同步来防止多线程并发交互。由于JDK11,内置了一个nullOutputStream。请参见windows上的另一个选项,NUL设备;IIRC它是“NUL:”作为“文件名”哦,哇,这真的是我第一次听说它!我要编辑这篇文章。谢谢!但是+1,因为这是正确的独立于平台的答案。不过,我也会重写write(byte[],int,int),以提高效率。我将指出,在大多数情况下,您可能应该在finally块中恢复原始的OutputStream。Apache Commons IO中有新的NullOutputStream。我在哪里可以获得NullPrintStream?哪个库?或者我需要自己创建类?我的代码确实需要它……这绝对是s的一个救命稻草ilencing stdout。对System.out.anything的任何后续调用都将导致抛出NullPointerException。如果这对您有效,那么您必须在某个地方捕获异常。虽然这可能是您想要做的(使System.out快速失败并发出噪音),但这肯定不是OP所要求的,并且它也不适用于他的示例代码