Hi,
This is driving me crazy... I'm writing code in Groovy (which runs on Java), and I'm trying to redirect stdout to a string, run some code, then restore stdout, but after I redirect it, I can't restore it -- it doesn't print to stdout anymore.
Here's my code:
It prints to stderr if I comment out the lines that redirect stderr, but no matter what I do, I can't get it to print to stdout after restoring oldOut. Everything I see online says it should work, so all I can think is that it must be something stupid that Groovy is doing. Any ideas?Code:// Redirect stdout & stderr to ByteArrayOutputStreams. ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); PrintStream oldOut = System.out; PrintStream oldErr = System.err; System.setOut( new PrintStream( out ) ); // System.setErr( new PrintStream( err ) ); String stdout; String stderr; try { try { app.parseCmdLine( args ); } finally { stdout = out.toString(); stderr = err.toString(); // Restore normal stdout & stderr. System.setOut( oldOut ); // System.setErr( oldErr ); } } catch ( Throwable e ) { System.setOut( oldOut ); // System.setErr( oldErr ); System.err.println( "An exception was caught when running: ${args}" ); System.out.println( "*** This should go to stdout." ); // This doesn't print to stdout! throw e; }