How to intercept System.out.write(bytes) and redirect it to a file?
===

I am new to Java and JUnit. I need some help implement a JUnit test case.

Below is the piece of code to be tested.

    public static void printHelp()
    {
       try
        {
            byte[] bytes = new byte[1024 * 4];
            InputStream is = AClassName.class.getResourceAsStream("readme.txt");
            while (is.available() > 0) {
                is.read(bytes, 0, bytes.length);
                System.out.write(bytes);
            }
        }
        catch(Exception x)
        {
            System.err.println(x.getMessage());
            System.exit(-1);
        }
    }

The test case I have in my mind is somewhat like this:

1) Intercept System.out.write(bytes) in printHelp();<br>
2) redirect the outputs to a temp file, e.g. /tmp/temp.txt;<br>
3) diff readme.txt and /tmp/temp.txt.

BTW, I know the piece of codes above has a bug - the array bytes may have residuals of the previous lines when writing out the last a few bytes of the file readme.txt. I can manually reproduce the bug. And I want to write a JUnit test case to cover this test. However, I don't know how to intercept System.out.write(bytes) in printHelp(), could someone show me a sample codes?

I did a bit search in this forum and found a few posts that could be related, e.g. this one: http://stackoverflow.com/questions/3384631/how-to-intercept-method-call-of-a-class. However, I could not understand it.

Thank you so much for your help.