A stream or reader is opened and used in one expression, so nothing ever closes it
What it finds
FileInputStream(path).readBytes() and file.bufferedReader().readLine() open a stream and read from it in one expression, and nothing holds the stream to close it: the file handle stays open until the garbage collector finalizes it, if ever. In a server or a loop the process runs out of file handles; on Windows the file cannot be deleted or renamed meanwhile. FileWriter(file).write(text) is worse: the text sits in the writer's buffer and may never reach the file. use { }, or File.readBytes(), readText() and writeText(), which close for themselves, avoid that.
Reported for readBytes, readText, readLine, read, lines, copyTo, write, append, print and println called directly on a stream or reader opened in the same expression: by a constructor such as FileInputStream, FileReader, FileWriter or PrintWriter, by openStream(), or by inputStream(), reader(), bufferedReader(), outputStream(), writer() or bufferedWriter() on a file.
From the rule's source, unclosed_stream_in_chain.rs.
fun load(path: String, file: File, log: File, out: Writer): ByteArray { val bytes = FileInputStream(path).readBytes()tx0 reports: the stream opened by FileInputStream is never closed after readBytes val first = file.bufferedReader().readLine()tx0 reports: the stream opened by bufferedReader() is never closed FileWriter(log).write("done")tx0 reports: never closed after write val text = FileReader(file).buffered().readText()tx0 reports: never closed val page = URL(path).openStream().readBytes()tx0 reports: the stream opened by openStream() val safe = FileInputStream(path).use { it.readBytes() } val whole = file.readBytes() PrintWriter(out).println("x") val json = parser.reader().readText() return bytes + safe + whole} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/kotlin:unclosed-stream-in-chain" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/kotlin:unclosed-stream-in-chain] reason="..."tx0 explain tx0/kotlin:unclosed-stream-in-chain shows the same in the terminal. Found a false positive? Report it.