The following code demonstrates a very easy and simple way to redirect Java System.out
and System.err
streams to both a File and Console.
For some reason, Googling for "Java stdout redirect to File and Console" does not result in any easy answers on the first few pages. The answer being so insanely simple, I decided to quickly write the method here, in the hopes that future programmers won't have to spend more than a few minutes on such an issue.
The issue being, of course, how does one use the methods in System.out
or System.err
to print to both a file and the console without having to resort to ridiculous extremes? In short, the answer is to wrap multiple OutputStream
s into a single OutputStream
class implementation and construct a PrintStream
instance on this implementation, and then set this PrintStream
implementation on System
.
So first define your MultiOutputStream
class:
public class MultiOutputStream extends OutputStream
{
OutputStream[] outputStreams;
public MultiOutputStream(OutputStream... outputStreams)
{
this.outputStreams= outputStreams;
}
@Override
public void write(int b) throws IOException
{
for (OutputStream out: outputStreams)
out.write(b);
}
@Override
public void write(byte[] b) throws IOException
{
for (OutputStream out: outputStreams)
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
for (OutputStream out: outputStreams)
out.write(b, off, len);
}
@Override
public void flush() throws IOException
{
for (OutputStream out: outputStreams)
out.flush();
}
@Override
public void close() throws IOException
{
for (OutputStream out: outputStreams)
out.close();
}
}
Next construct your PrintStream
instance and set it on System
:
try
{
FileOutputStream fout= new FileOutputStream("stdout.log");
FileOutputStream ferr= new FileOutputStream("stderr.log");
MultiOutputStream multiOut= new MultiOutputStream(System.out, fout);
MultiOutputStream multiErr= new MultiOutputStream(System.err, ferr);
PrintStream stdout= new PrintStream(multiOut);
PrintStream stderr= new PrintStream(multiErr);
System.setOut(stdout);
System.setErr(stderr);
}
catch (FileNotFoundException ex)
{
}
Now you can go bananas and use System.out
or System.err
to write whatever you like, and it will be written to both the console and a file:
System.out.println("Holy Rusty Metal Batman! I can't believe this was so simple!");
System.err.println("God I hate you Robin.");
Goodbye, have a nice time!