开发者

Writing to the real STDOUT after System.setOut

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 = System.out;
System.setOut(new MyMagicPrintStream());
ps.println("foo");

Unfortunately, the details of the System clas开发者_StackOverflow中文版s' implementation means that in my example, "foo" gets sent to MyMagicPrintStream instead of the real stdout.

Does anyone know how to get references to the real/original OutputStreams?

Thanks.

PS: This will otherwise result in a StackOverflowError <-- for SEO.


try this:

PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out))


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜