在Java中,如何为特定的方法调用重定向System.err?

问题描述 投票:0回答:2

比如我有一些方法 method() 中的一个子方法,它调用了一系列对应于堆栈跟踪结构的方法。可能其中一个'子方法'调用打印到System.err stderr。有没有办法阻止所有与该方法相关的打印?我发现 本页 其中解释了如何通过临时重定向System.err来做到这一点,但我担心这可能会导致其他错误(我确实想跟踪)不出现在控制台中。

java console stdout stderr
2个回答
0
投票

你可以尝试在methods调用前存储原来的PrintStream和Override,调用后再将其还原回来。

 public static void main(String[] args) {
        // Before methods' invocation
        final PrintStream orgErr = System.err;

        System.setErr(new PrintStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {

            }
        }));

        callMethod();

        // After methods' invocation
        System.setErr(orgErr);
    }

    static void callMethod() {
        try {
            throw new RuntimeException("failed");
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

0
投票

除非你正在运行多个线程,否则使用你链接到的帖子中的方法应该是可行的(除了System.setErr而不是System.setOut外

public void method(){
    //This submethod will print errors
    submethod1();

    PrintStream original = System.err;
    System.setErr(new PrintStream(new OutputStream(){
        public void write(int i){ }
    }));

    //This submethod will NOT print errors
    submethod2();

    System.setErr(original);

    //This submethod will print errors
    submethod3();
}

只要你在调用任何你想要的错误的子方法之前,回到原来的状态,你应该就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.