Redirect lots of system.out.println's to a .txt file

CodyBugstein picture CodyBugstein · Jan 27, 2013 · Viewed 9.7k times · Source

Possible Duplicate:
Print java output to a file

In a Java program, I have a long method, (which I don't think is important to post since it's not vital to the question) that has a large number of println statements to print status updates to the console.

Instead of having these printout to the console, I'd like them to go into a txt file where I can store them and review them later.

Is there a simple way to redirect the output without manually going through each println statement?

If not, what's the best way to go about this?

Answer

iainmackay85 picture iainmackay85 · Jan 27, 2013

I have had to do this before, it isn't very neat and I hope you aren't doing it for a final piece of code, but I did:

PrintStream ps = new PrintStream("\file.txt");
PrintStream orig = System.out;
System.setOut(ps);
//TODO: stuff with System.out.println("some output");
System.setOut(orig);
ps.close();