Redirect System.out.println
Here is how to capture prints to System.out, and then put things back in order :
// Start capturing
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));
// Run what is supposed to output something
...
// Stop capturing
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
// Use captured content
String content = buffer.toString();
buffer.reset();
I had a similar need once. I needed to intercept the output of some 3rd party component and react on a error message. The concept looks like this:
private class Interceptor extends PrintStream
{
public Interceptor(OutputStream out)
{
super(out, true);
}
@Override
public void print(String s)
{//do what ever you like
super.print(s);
}
}
public static void main(String[] args)
{
PrintStream origOut = System.out;
PrintStream interceptor = new Interceptor(origOut);
System.setOut(interceptor);// just add the interceptor
}
The better solution is to go through and change all the println statements to use a proper logging library. What you're trying to do is a big hack.
The System class has a setOut
and setErr
that can be used to change the output stream to, for example, a new PrintStream
with a backing File
or, in this case, probably another stream which uses your logging subsystem of choice.
Keep in mind you may well get yourself into trouble if you ever configure your logging library to output to standard output or error (of the infinite recursion type, possibly).
If that's the case, you may want to just go and replace your System.out.print
-type statements with real logging calls.