I/O
io4NioFilesAndPaths
- Path
- pkg9io/io4NioFilesAndPaths.java
- Package
- pkg9io
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg9io/io4NioFilesAndPaths.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg9io;2 3import java.io.IOException;4import java.nio.charset.StandardCharsets;5import java.nio.file.Files;6import java.nio.file.Path;7import java.nio.file.Paths;8import java.nio.file.StandardOpenOption;9import java.util.List;10import java.util.stream.Stream;11 12/*13 * io4NioFilesAndPaths.java14 * ------------------------15 * Modern file I/O: java.nio.file.Path + Files (Java 7+, the recommended API).16 *17 * DEFINITION:18 * NIO.2 replaces java.io.File with Path (a typed path) and Files (a toolbox19 * of static helpers). It is shorter, safer, charset-aware, and more powerful.20 *21 * KEY POINTS:22 * - Files.writeString / readString (Java 11+) do whole-file text in one line.23 * - Files.write/readAllLines work with List<String>; default charset is UTF-8.24 * - StandardOpenOption controls CREATE / APPEND / TRUNCATE behavior.25 * - Path offers resolve(), getFileName(), getParent() for safe composition.26 */27public class io4NioFilesAndPaths {28 29 public static void main(String[] args) throws IOException {30 Path dir = Files.createTempDirectory("io4");31 Path file = dir.resolve("data.txt"); // dir + "data.txt", portably32 33 System.out.println("file name : " + file.getFileName());34 System.out.println("parent : " + file.getParent());35 36 // Whole-file write/read as a String (Java 11+)37 Files.writeString(file, "first line\n", StandardCharsets.UTF_8);38 Files.writeString(file, "appended line\n", StandardOpenOption.APPEND);39 System.out.println("\nreadString():\n" + Files.readString(file).stripTrailing());40 41 // Work with lists of lines42 Files.write(file, List.of("alpha", "beta", "gamma")); // overwrites43 List<String> lines = Files.readAllLines(file);44 System.out.println("\nreadAllLines(): " + lines);45 46 // Stream lines lazily (good for huge files — does not load everything)47 System.out.println("\nUppercased via stream:");48 try (Stream<String> s = Files.lines(file)) {49 s.map(String::toUpperCase).forEach(l -> System.out.println(" " + l));50 }51 52 // Metadata53 System.out.println("\nsize=" + Files.size(file) + " bytes, exists=" + Files.exists(file));54 55 // Recursive cleanup (delete files, then the directory)56 try (Stream<Path> walk = Files.walk(dir)) {57 walk.sorted((a, b) -> b.getNameCount() - a.getNameCount()) // children first58 .forEach(p -> { try { Files.deleteIfExists(p); } catch (IOException ignored) {} });59 }60 System.out.println("Cleaned up: exists=" + Files.exists(dir));61 62 // Paths.get is the older factory (equivalent to Path.of)63 Path p = Paths.get("a", "b", "c.txt");64 System.out.println("\nPaths.get -> " + p);65 }66}