Skip to content

Stream not closed (ARCH4081)

Key java.performance.stream-not-closed · Severity error · Category performance

If a Reader, Writer, or stream is opened and not closed, its underlying file handle stays held. Once enough handles leak, the app crashes with “too many open files”.

public String read(Path file) throws IOException {
BufferedReader r = Files.newBufferedReader(file);
return r.readLine();
}
public String read(Path file) throws IOException {
try (BufferedReader r = Files.newBufferedReader(file)) {
return r.readLine();
}
}

Open streams and readers inside try-with-resources so they are closed in all cases.