Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to the real STDOUT after System.setOut

Tags:

java

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 class' 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.

like image 402
Jim Avatar asked Jul 27 '10 02:07

Jim


People also ask

What does system setOut do?

The static System. setOut() method is used to reassign the standard output stream. This method first uses the checkPermission() method to check for the security manager and its permissions.

What is PrintStream in Java?

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.


2 Answers

try this:

PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out)) 
like image 71
fqsxr Avatar answered Sep 22 '22 14:09

fqsxr


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 
like image 36
RealHowTo Avatar answered Sep 20 '22 14:09

RealHowTo