2

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?

Community
  • 1
  • 1
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • 4
    You can certainly redirect the standard output. Look at `System.setOut(PrintStream out)` in the [System class](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html). The PrintStream is one of your own that outputs to a file. – Hovercraft Full Of Eels Jan 27 '13 at 21:11
  • @HovercraftFullOfEels This is a perfectly upvoteable answer :) – Sergey Kalinichenko Jan 27 '13 at 21:13
  • 1
    @dasblinkenlight: I've reached my up-vote receiving limit, and regardless, I'm 100% sure that this question is a duplicate and in fact has been asked many many times, but I'm too lazy to look up for duplicates. – Hovercraft Full Of Eels Jan 27 '13 at 21:16

3 Answers3

11

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();
iainmackay85
  • 144
  • 2
4

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1
  1. add extra parameter to the method , PrintStream out
  2. search&replace System.out with out in your method.
  3. done.
  4. (call method with a PrintStream wrapped around a FileOutputStream)
jtahlborn
  • 52,909
  • 5
  • 76
  • 118