【发布时间】:2011-06-15 12:02:18
【问题描述】:
我尝试使用以下代码将 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!!!
有人有什么想法吗?
【问题讨论】:
-
我在我的系统上看到两条线都很好。我正在使用 Java 6 更新 22。
-
顺便说一句:当心在没有更广泛的同步的情况下像这样操纵 System.out 以防止多个线程的并发交互。
-
从JDK11开始,内置了一个nullOutputStream。见my answer below