I'm trying to copy all the data from written to the console (incl errors, system.outs.. est) and write it to a text file. I know how to write it, but i have no clue how to get the data out of the actual console(Not the log file). Any ideas how this can be done?
Lila Fowler wrote:Some errors that appear in the console don't necessarily appear in the log
When redirecting the console output to a file, you have to use "2>&1".
Otherwise, you'll only see standard output ...
Lili Fowler wrote:But the console is a default function in java, what part is actually accessing the original console data?Would
1. orgStream = System.out;
then contain the original data?
Well, printing to console output is indeed the default operation of stdin, stdout & stderr.
However with System.setXXX(...), you have the possibility to redirect it to e.g. a file.
So in above case it only contains the ref to the System.out, which is later used to restore the printing back to the console.
Here is my code, but it still doesn't write the exception to the file, and the things that do write to the file don't display in the console. I need the .txt file to be a mirror image of the console. Any ideas?
Here is my current code.
- get a reference to the old streams (lines 3-4)
- set up the new streams (lines 5-7)
- test the redirect (lines 8-9)
- throw a RuntimeException (line 10)
- run the finally block to restore the old streams (lines 29-30)
- exit the main method with the RuntimeException (JVM internals)
- print the RuntimeException to the default, restored standard error stream (JVM internals)
If you want to write everything to your custom print stream simply don't call lines 29 and 30. If the JVM exits it will restore the default output and error streams and close all file handles opened from that Java application for you.
How it would work:
From now on everything written to either System.out or System.err will be written to both the original System.out and the file.