我试图使用以下代码将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是跨平台的,而'/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();
}

10-01 23:52
查看更多