File: StreamResourceLeak.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (64 lines) | stat: -rw-r--r-- 2,292 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
The problem is described in the [javadoc] for `Files`.

## `Files.newDirectoryStream`

> When 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.list`

> The 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.walk`

> The 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 an `IllegalStateException`.

## `Files.find`

> The 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 an `IllegalStateException`.

## `Files.lines`

> The 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.

[javadoc]: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

## The solution

To ensure the stream is closed, always use try-with-resources. For example, when
using `Files.lines`, do this:

```java
String input;
try (Stream<String> stream = Files.lines(path)) {
  input = stream.collect(Collectors.joining(", "));
}
```

Not this:

```java
// the Reader is never closed!
String input = Files.lines(path).collect(Collectors.joining(", ");
```

## What about methods that return closeable streams? {#must-be-closed}

Methods that return `Stream`s that encapsulate a closeable resource can be
annotated with `com.google.errorprone.annotations.MustBeClosed` to ensure their
callers remember to close the stream.