London
London

Reputation: 15274

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?

Upvotes: 2

Views: 4564

Answers (5)

Howard
Howard

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

Robin Green
Robin Green

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

sverre
sverre

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

Matt Ball
Matt Ball

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

rich
rich

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

Related Questions