Search code examples
javafile-ioprintlnprintstream

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


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?


Solution

  • The System class has a static method, System.setOut(PrintStream out). All you have to do is create your own PrintStream that writes to a file, stuff it into this method and you're all set.

    Better less fragile solution: Don't use System.out.printFoo(...) but instead just use a logger, and change the logging levels as it suits your purposes at that time.