|
| 1 | +package com.winterbe.java8.samples.misc; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.BufferedWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.nio.file.Paths; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author Benjamin Winterberg |
| 13 | + */ |
| 14 | +public class Files1 { |
| 15 | + |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + testWalk(); |
| 18 | + testFind(); |
| 19 | + testList(); |
| 20 | + testLines(); |
| 21 | + testReader(); |
| 22 | + testWriter(); |
| 23 | + testReadWriteLines(); |
| 24 | + } |
| 25 | + |
| 26 | + private static void testWriter() throws IOException { |
| 27 | + try (BufferedWriter writer = |
| 28 | + Files.newBufferedWriter(Paths.get("res", "output.js"))) { |
| 29 | + writer.write("print('Hello World');"); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + private static void testReader() throws IOException { |
| 34 | + try (BufferedReader reader = |
| 35 | + Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) { |
| 36 | + System.out.println(reader.readLine()); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private static void testWalk() throws IOException { |
| 41 | + Path start = Paths.get("/Users/benny/Documents"); |
| 42 | + int maxDepth = 5; |
| 43 | + long fileCount = Files |
| 44 | + .walk(start, maxDepth) |
| 45 | + .filter(path -> String.valueOf(path).endsWith("xls")) |
| 46 | + .count(); |
| 47 | + System.out.format("XLS files found: %s", fileCount); |
| 48 | + } |
| 49 | + |
| 50 | + private static void testFind() throws IOException { |
| 51 | + Path start = Paths.get("/Users/benny/Documents"); |
| 52 | + int maxDepth = 5; |
| 53 | + Files.find(start, maxDepth, (path, attr) -> |
| 54 | + String.valueOf(path).endsWith("xls")) |
| 55 | + .sorted() |
| 56 | + .forEach(System.out::println); |
| 57 | + } |
| 58 | + |
| 59 | + private static void testList() throws IOException { |
| 60 | + Files.list(Paths.get("/usr")) |
| 61 | + .sorted() |
| 62 | + .forEach(System.out::println); |
| 63 | + } |
| 64 | + |
| 65 | + private static void testLines() throws IOException { |
| 66 | + Files.lines(Paths.get("res", "nashorn1.js")) |
| 67 | + .filter(line -> line.contains("print")) |
| 68 | + .forEach(System.out::println); |
| 69 | + } |
| 70 | + |
| 71 | + private static void testReadWriteLines() throws IOException { |
| 72 | + List<String> lines = Files.readAllLines(Paths.get("res", "nashorn1.js")); |
| 73 | + lines.add("print('foobar');"); |
| 74 | + Files.write(Paths.get("res", "nashorn1-modified.js"), lines); |
| 75 | + } |
| 76 | +} |
0 commit comments