Skip to content

Commit 70a38ae

Browse files
committed
Add proper try/with statements
1 parent 0c4f633 commit 70a38ae

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

src/com/winterbe/java8/samples/misc/Files1.java

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import java.nio.file.Path;
88
import java.nio.file.Paths;
99
import java.util.List;
10+
import java.util.stream.Stream;
1011

1112
/**
1213
* @author Benjamin Winterberg
@@ -49,34 +50,37 @@ private static void testReader() throws IOException {
4950
}
5051

5152
private static void testWalk() throws IOException {
52-
Path start = Paths.get("/Users/benny/Documents");
53+
Path start = Paths.get("");
5354
int maxDepth = 5;
54-
long fileCount = Files
55-
.walk(start, maxDepth)
56-
.filter(path -> String.valueOf(path).endsWith("xls"))
57-
.count();
58-
System.out.format("XLS files found: %s", fileCount);
55+
try (Stream<Path> stream = Files.walk(start, maxDepth)) {
56+
long fileCount = stream
57+
.filter(path -> String.valueOf(path).endsWith(".js"))
58+
.count();
59+
System.out.format("JS files found: %s", fileCount);
60+
}
5961
}
6062

6163
private static void testFind() throws IOException {
62-
Path start = Paths.get("/Users/benny/Documents");
64+
Path start = Paths.get("");
6365
int maxDepth = 5;
64-
Files.find(start, maxDepth, (path, attr) ->
65-
String.valueOf(path).endsWith("xls"))
66-
.sorted()
67-
.forEach(System.out::println);
66+
try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) ->
67+
String.valueOf(path).endsWith(".js"))) {
68+
stream.sorted().forEach(System.out::println);
69+
}
6870
}
6971

7072
private static void testList() throws IOException {
71-
Files.list(Paths.get("/usr"))
72-
.sorted()
73-
.forEach(System.out::println);
73+
try (Stream<Path> stream = Files.list(Paths.get("/usr"))) {
74+
stream.sorted().forEach(System.out::println);
75+
}
7476
}
7577

7678
private static void testLines() throws IOException {
77-
Files.lines(Paths.get("res", "nashorn1.js"))
78-
.filter(line -> line.contains("print"))
79-
.forEach(System.out::println);
79+
try (Stream<String> stream = Files.lines(Paths.get("res", "nashorn1.js"))) {
80+
stream
81+
.filter(line -> line.contains("print"))
82+
.forEach(System.out::println);
83+
}
8084
}
8185

8286
private static void testReadWriteLines() throws IOException {

0 commit comments

Comments
 (0)