A file, socket or archive is opened into a local variable and never closed nor handed on

tx0/java:unclosed-resourcedefaultwarningbug, cwe-772

What it finds

FileInputStream in = new FileInputStream(path); opens a file handle that only close() gives back. A local variable that is never closed, never passed on, never returned and never stored leaks the handle every time the method runs; enough of them and the process runs out of file descriptors. try (FileInputStream in = ...) closes it on every path.

Reported are local variables initialized with a new file, socket or archive object, directly or wrapped in other streams, whose every use is a call of a method other than close on them. Calls that hand on the underlying handle, as getChannel or getInputStream, count as handing the resource on.

From the rule's source, unclosed_resource.rs.

Example from the rule's tests
import java.io.FileInputStream;import java.io.FileReader;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream; class Files {  int first(String path) throws IOException {    FileInputStream in = new FileInputStream(path);tx0 reports: in is opened but never closed    return in.read();  }   String line(String path) throws IOException {    BufferedReader reader = new BufferedReader(new FileReader(path));tx0 reports: reader is opened but never closed    return reader.readLine();  }   int closed(String path) throws IOException {    FileInputStream in = new FileInputStream(path);    int b = in.read();    in.close();    return b;  }   InputStream handed(String path) throws IOException {    FileInputStream in = new FileInputStream(path);    return in;  }   int managed(String path) throws IOException {    try (FileInputStream in = new FileInputStream(path)) {      return in.read();    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:unclosed-resource" = "off"

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/java:unclosed-resource] reason="..."

tx0 explain tx0/java:unclosed-resource shows the same in the terminal. Found a false positive? Report it.