Writing to the real STDOUT after System.setOut

后端 未结 4 543
栀梦
栀梦 2020-12-24 06:43

I\'m trying to intercept System.out and System.err, but maintain the ability to write to the original streams directly when necessary.

PrintStream ps = Syste         


        
4条回答
  •  有刺的猬
    2020-12-24 07:13

    PrintStream original = new PrintStream(System.out); basically wraps the existing reference - so if System.setOut() was changing it - there should be no difference. That's probably an issue with particular JVM, but I would rather guess that something was wrong with the MyMagicPrintStream, or the code writing to the stdout. Actually the following piece of code does exactly what is expected on Sun 1.6.0_20-b02 for Windows:

    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    public class SystemOutTest {
    
    public static void main(String args[]) {
        try {
            PrintStream ps = System.out;
            System.setOut(new PrintStream(new FileOutputStream("stdout.log")));
    
            System.out.println("foo");  
            ps.println("bar");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    }
    

    "foo" goes to stdout.log, "bar" to the console.

    Also, if you need to access the original stdin / out assigned of JVM startup - you can use System.console(); (just remember - it can be null!)

提交回复
热议问题