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?

4
  • You can use a logger for doing this. Take a look at Apache log4j Commented Dec 6, 2017 at 9:33
  • 1
    One might also opt to handle this at the shell level using tee or similar. For example, java MyApp | tee logfile.txt. See 12factor.net/logs for further thoughts on logging to file vs stdout. Commented Dec 6, 2017 at 9:33
  • @GhostCat , my question already has an answer (see duplicate question's answer). I used that solution: TeeOutputStream from Apache Commons Commented Dec 8, 2017 at 8:01
  • @GhostCat , I have used the solution: TeeOutputStream from Apache Commons (see duplicate question's answer) Commented Jul 19, 2018 at 14:55

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.