You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out);
The second statement is key. It changes the value of the supposedly "final" System.out attribute to the provided PrintStream value.
There are similar methods ( setIn and setErr ) for changing standard input and error streams; see javadocs java.lang.System for details.
A more general version of the above:
PrintStream out = new PrintStream( new FileOutputStream("output.txt", append), autoFlush); System.setOut(out);
If append is true , the stream will append to the existing file instead of truncating it. If autoflush is true , the output buffer will be flushed when a byte array is written, when one of the println methods is called, or when \n written.
I just wanted to add that it is usually better to use a logging subsystem like Log4j , Logback or standard Java java.util.logging . subsystem. They provide detailed logging control using runtime configuration files, support for scrolling log files, channels in the system log, etc.
Also, if you are not βkeeping a journal,β consider the following:
With typical shells, you can redirect standard output (or standard error) to a file on the command line; eg,
$ java MyApp > output.txt
See the shell manual or the manual for more information.
You can modify your application so that it uses the out stream, passed as a parameter to the method, or through a single injection or dependency injection, instead of writing to System.out .
Changing System.out can cause unpleasant surprises for other code in your JVM that does not expect this to happen. (A properly designed Java library will avoid dependencies on System.out and System.err , but you might not be lucky.)
Stephen C Jan 03 '09 at 8:04 2010-01-03 08:04
source share