2
\$\begingroup\$

I wanted to have a simple way to capture all sysout for a block of code. Ended up with this:

fun captureSysOut(block: () -> Any?): String {
    val originalSysOut = System.out
    val out = ByteArrayOutputStream(2048)
    System.setOut(PrintStream(out))
    return try {
        block()
        String(out.toByteArray())
    } finally {
        System.setOut(originalSysOut)
    }
}

Example usage:

val capturedOutput = captureSysOut { 
    println("this will not print, but be saved into the variable")
}

I am also considering using a OutputStream wrapper that duplicates stream into multiple outputs so that the captured output is saved into local variable but also still written into the console at the same time, for example TeeOutputStream, but don't want to overcomplicate things.

\$\endgroup\$
2
  • \$\begingroup\$ I gotta ask: Why do you need this? What are you going to do with this? It seems to me like you might want to look for a logging library and use an appender that does something whenever there is some output? \$\endgroup\$ Oct 13, 2022 at 21:10
  • 1
    \$\begingroup\$ Imagine you don't have control of the code within this block. I use it in code benchmarking tool. I run different algorithms (with same results) on same structures and then record sysout, execution time and resulting data. \$\endgroup\$
    – K.H.
    Oct 13, 2022 at 21:14

1 Answer 1

2
\$\begingroup\$

Don't forget to flush the stream before setting it back to the original in the finally block.

This is not thread-safe for any other code that prints to stdout, so be careful with that.

The buffer of ByteArrayOutputStream automatically grows as data is written to it so you don't have to specify the starting size which may be too much if you're only printing a couple symbols. It's not that important though.

I would not name a variable out since its a keyword in Kotlin and may be confusing. In this case it's very clear what it stands for so this is not that important either.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.