Reputation: 15274
How to print java output to both shell console and at the same time in some file? is that possible?
Upvotes: 2
Views: 4564
Reputation: 39197
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);
}
}));
Upvotes: 6
Reputation: 33063
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.
Upvotes: 0
Reputation: 6919
You can use System.setOut()
to redirect System.Out
to a custom OutputStream
that duplicates its output to both the console and a file.
Upvotes: 2
Reputation: 359826
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.
Upvotes: 0
Reputation: 19414
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
Upvotes: 0