Writing to the real STDOUT after System.setOut

后端 未结 4 550
栀梦
栀梦 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!)

    0 讨论(0)
  • 2020-12-24 07:14

    Try something like this :

      PrintStream original = new PrintStream(System.out);
    
      // replace the System.out, here I redirect to NUL
      System.setOut(new PrintStream(new FileOutputStream("NUL:")));
      System.out.println("bar");  // no output
    
      // the original stream is still available 
      original.println("foo");  // output to stdout
    
    0 讨论(0)
  • 2020-12-24 07:15
    PrintStream original = System.out;
    System.setOut(new MyMagicPrintStream());
    
    // This will print to MyMagicPrintStream();
    System.out.println("foo for MyMagicPrintStream");
    
    
    System.setOut(original);
    
    // This will print to original print stream;
    System.out.println("foo for original print stream (stdout)");
    

    This works for me.

    0 讨论(0)
  • try this:

    PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out))
    
    0 讨论(0)
提交回复
热议问题