How to print java output to both shell console and at the same time in some file? is that possible?
-
2Most logging facilities support this kind of thing. For example, adding a ConsoleAppender and a FileAppender with Log4J will do this. Somebody mentioned SLF4J - which is true although its just a facade. As far as I know, you still need to configure which logging facility it will use behind the scenes. – Nick Apr 17 '11 at 18:12
5 Answers
You can include the following lines at the start of your program:
final PrintStream origout = System.out;
final PrintStream fileout = new PrintStream(file);
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
origout.write(b);
fileout.write(b);
}
}));

- 38,639
- 9
- 64
- 83
-
I am putting this at the beginning of my main method but I'm getting all sorts of errors, including undefined constructors etc. I imported all the appropriate packages. Please help – CodyBugstein Feb 03 '13 at 20:22
-
I got it to work by replacing new OutputStream with fileout. However, this is causing me to not be able to see any output in the console, rather I can only see output in the .txt file. How can I output to both? – CodyBugstein Feb 03 '13 at 20:31
You can use System.setOut()
to redirect System.Out
to a custom OutputStream
that duplicates its output to both the console and a file.

- 6,768
- 2
- 27
- 35
You can write to a console. And write to a file. You can thread them seperately so they're not dependent upon each other.
There isn't an API for doing both at the same time that I'm aware of (not that that says too much, it should be trivial to write one).
Edit: Have I misunderstood? Do you mean from Java code or just piping the output of the java binary to console and a file? In which case you could do something like:
java Main 2>&1 | tee -a Load.log

- 18,987
- 11
- 75
- 101
You can do this with an SLF4J implementation, like Logback. This is how JBoss (by default) sends the output to the console as well as to a log file.

- 354,903
- 100
- 647
- 710
-
@downvoter: any comments? Your feedback can only help me improve my answer, or convince me to remove it if I'm just plain wrong. – Matt Ball Apr 17 '11 at 21:07
-
This needs more explanation. It's more of a comment than an answer – CodyBugstein Feb 03 '13 at 20:17
The easiest way (because it involves no real programming) is to use the tee command in Linux, Mac OS X or Windows Powershell, like this:
java MyProg | tee outputfile.txt
This works for any programming language, not just Java.

- 32,079
- 16
- 104
- 187