Print java output to a file
How to print java output开发者_运维问答 to both shell console and at the same time in some file? is that possible?
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);
}
}));
You can use System.setOut()
to redirect System.Out
to a custom OutputStream
that duplicates its output to both the console and a file.
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
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.
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.
精彩评论