Madhav Datt Madhav Datt - 1 month ago 6
Java Question

Checking if 'stderr' is empty in a Java program

Is there a way to check during a Java program if something was printed to the

stderr
till that point? As a dummy example,

if (something == somethingElse)
{
System.err.println("This is a message");
}

// Here, I want to check if stderr is empty, or if something was printed to it

Answer

Sure, that's possible (although only advised as part of a test setup, not as part of the application itself).

You can redirect System.err to another PrintStream. If that PrintStream captures the output in a buffer, then you can check that buffer later.

If you also want to see the output on the original error stream, as @ElliotFrisch suggested, then you need to do more work: you need to make a custom PrintStream subclass that directs output to the original System.err as well as to your buffer.

But if this is just to capture the output for a unit test, you probably don't need that - you probably want to assert that the output contains something.

    // Set up alternate System.err PrintStream that prints to a buffer
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream p = new PrintStream(bytes, true, "UTF-8");
    System.setErr(p);

    if (something == somethingElse) {
        System.err.println("This is a message");
    }

    // Here, I want to check if stderr is empty, or if something was printed
    // to it

    // Capture what was printed so far
    String printedSoFar = bytes.toString("UTF-8");
Comments