Writing to the real STDOUT after System.setOut

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

try this:

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

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!)


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.

Tags:

Java