Tuesday, September 24, 2013

Java : Redirect/Write console output to a file

Sometimes we would like to save the output from console into a file and to do this we use some stream writer/reader to read from console and write to a file.

But this can be done in much easier way as follows. Add the following code at the beginning of the program:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
Now the default behaviour of out is changed to PrintStream out, and the output is redirected to the file provided above.

To reset the standard behaviour, add the following code