在Java中,如何将System.out重定向到null然后再返回到stdout? [英] In Java, how can I redirect System.out to null then back to stdout again?

查看:446
本文介绍了在Java中,如何将System.out重定向到null然后再返回到stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

任何人都有任何想法?

推荐答案

男,这不太好,因为Java是跨平台的,'/ dev / null'是Unix特有的(显然在Windows上有一个替代方案,阅读评论)。因此,您最好的选择是创建一个自定义OutputStream来禁用输出。

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();
}

这篇关于在Java中,如何将System.out重定向到null然后再返回到stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆