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.