1

There is a Java command to redirect standard output to a file or back to the standart output:

PrintStream stdout = System.out;
System.setOut(new PrintStream(logFile));
// ...
System.setOut(stdout); 

But I need to have both of them. Is it possible to set standard output in Java both to the file and to the standard output?

Ivan Gerasimenko
  • 2,381
  • 3
  • 30
  • 46

2 Answers2

3

I am not aware of a standard class doing that, but it is pretty simple:

  • first fetch the "ordinary" stdout PrintStream
  • write your own PrintStream implementation that writes to a file and to another Printstream
  • simply pass the original stdout to your new DoublePrintingPrintStream, and use setOut() to use that "double printing" stream

Alternatively, there are tools such as tee that can do that for you. So instead of bothering your Java code with that - simply have something outside read stdout, print to console and write to a file.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
-1

Use a Logger. If needed with a Layout just giving the input. Then you can, even in code add both a ConsoleAppender and a FileAppender.

Also better code style. And that "logFile" is telling.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138