Alternate names: FilesLinesLeak
The problem is described in the javadoc for Files.
Files.newDirectoryStreamWhen not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
Files.listThe returned stream encapsulates a
DirectoryStream. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream’s close method is invoked after the stream operations are completed.
Files.walkThe returned stream encapsulates one or more
DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream’s close method is invoked after the stream operations are completed. Operating on a closed stream will result in anIllegalStateException.
Files.findThe returned stream encapsulates one or more
DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream’s close method is invoked after the stream operations are completed. Operating on a closed stream will result in anIllegalStateException.
Files.linesThe returned stream encapsulates a
Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream’s close method is invoked after the stream operations are completed.
To ensure the stream is closed, always use try-with-resources. For example, when
using Files.lines, do this:
String input;
try (Stream<String> stream = Files.lines(path)) {
input = stream.collect(Collectors.joining(", "));
}
Not this:
// the Reader is never closed!
String input = Files.lines(path).collect(Collectors.joining(", ");
Methods that return Streams that encapsulate a closeable resource can be
annotated with com.google.errorprone.annotations.MustBeClosed to ensure their
callers remember to close the stream.
Suppress false positives by adding the suppression annotation @SuppressWarnings("StreamResourceLeak") to the enclosing element.