forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFiles1.java
More file actions
87 lines (76 loc) · 2.71 KB
/
Files1.java
File metadata and controls
87 lines (76 loc) · 2.71 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.winterbe.java8.samples.misc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* @author Benjamin Winterberg
*/
public class Files1 {
public static void main(String[] args) throws IOException {
testWalk();
testFind();
testList();
testLines();
testReader();
testWriter();
testReadWriteLines();
testReaderLines();
}
private static void testReaderLines() throws IOException {
try (BufferedReader reader =
Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) {
long countPrints = reader.lines()
.filter(line -> line.contains("print"))
.count();
System.out.println(countPrints);
}
}
private static void testWriter() throws IOException {
try (BufferedWriter writer =
Files.newBufferedWriter(Paths.get("res", "output.js"))) {
writer.write("print('Hello World');");
}
}
private static void testReader() throws IOException {
try (BufferedReader reader =
Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) {
System.out.println(reader.readLine());
}
}
private static void testWalk() throws IOException {
Path start = Paths.get("/Users/benny/Documents");
int maxDepth = 5;
long fileCount = Files
.walk(start, maxDepth)
.filter(path -> String.valueOf(path).endsWith("xls"))
.count();
System.out.format("XLS files found: %s", fileCount);
}
private static void testFind() throws IOException {
Path start = Paths.get("/Users/benny/Documents");
int maxDepth = 5;
Files.find(start, maxDepth, (path, attr) ->
String.valueOf(path).endsWith("xls"))
.sorted()
.forEach(System.out::println);
}
private static void testList() throws IOException {
Files.list(Paths.get("/usr"))
.sorted()
.forEach(System.out::println);
}
private static void testLines() throws IOException {
Files.lines(Paths.get("res", "nashorn1.js"))
.filter(line -> line.contains("print"))
.forEach(System.out::println);
}
private static void testReadWriteLines() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("res", "nashorn1.js"));
lines.add("print('foobar');");
Files.write(Paths.get("res", "nashorn1-modified.js"), lines);
}
}