Redirect System.out and System.err

后端 未结 4 1349
情话喂你
情话喂你 2020-12-05 19:37

I have some legacy code (or rather some code we don\'t control but we have to use) that writes a lot of statements to system.out/err.

At the same time, we are using

4条回答
  •  我在风中等你
    2020-12-05 20:22

    Take a look at the constructors provided by PrintStream. You can pass the logging framework OutputStream directly to PrintStream, then set the System.out and System.err to use the PrintStream.

    Edit: Here's a simple test case:

    public class StreamTest
    {
        public static class MyOutputStream extends FilterOutputStream
        {
            public MyOutputStream(OutputStream out)
            {
                super(out);
            }
    
            @Override
            public void write(byte[] b, int off, int len) throws IOException
            {
                byte[] text = "MyOutputStream called: ".getBytes();         
                super.write(text, 0, text.length);
                super.write(b, off, len);
            }
        }
    
        @Test   
        public void test()
        {       
            //Any OutputStream-implementation will do for PrintStream, probably
            //you'll want to use the one from the logging framework
            PrintStream outStream = new PrintStream(new MyOutputStream(System.out), true);  //Direct to MyOutputStream, autoflush
            System.setOut(outStream); 
    
            System.out.println("");
            System.out.print("TEST");
            System.out.println("Another test");
        }
    }
    

    The output is:

    MyOutputStream called: 
    MyOutputStream called: TESTMyOutputStream called: Another testMyOutputStream called: 
    

    The second line has an "empty" call (MyOutputStream called: -output and then nothing after it), because println will first pass the Another test -string to the write-method, and then calls it again with a line feed.

提交回复
热议问题