Sub topic 1
Representing Locations with `Path`
Prerequisites.
This chapter assumes basic Java classes, String, List, streams, and checked exceptions. You should also know how try and catch work. The examples use Java 11 or later.
Representing locations with `Path`
A Path represents a file or directory location. It does not mean that the location exists. Creating a Path only creates an object describing the location.
Use Path.of instead of building path strings manually. Java applies the correct separator for the operating system.
import java.nio.file.Path;
public class PathDemo {
public static void main(String[] args) {
Path base = Path.of("data");
Path file = base.resolve("notes.txt");
System.out.println(file);
System.out.println(file.getFileName());
System.out.println(Path.of("data/../data/./notes.txt").normalize());
}
}Combining and cleaning paths
resolve appends one path to another. normalize removes redundant . and .. elements. These operations do not access the file system.
relativize calculates a path from one location to another. Both paths should normally be either relative or absolute.
The `Files` class at a glance
Files is a utility class containing operations that use Path objects. It can read, write, copy, move, delete, and inspect files and directories.
| Task | Common method |
|---|---|
| Read all text | `Files.readString(path)` |
| Write all text | `Files.writeString(path, text)` |
| Check existence | `Files.exists(path)` |
Character encodings: always know your charset
A character encoding maps characters to bytes. UTF-8 is a common encoding that supports many languages. Methods such as readString use UTF-8 by default in modern Java. For APIs that accept a charset, specify StandardCharsets.UTF_8 explicitly so the choice is clear.
Reading a whole file into memory
Files.readString returns the complete file as one String. Files.readAllLines returns a List<String>, with one element per line. Both load the complete file into memory, so use buffered or streaming APIs for large files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class SmallFiles {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "first\nsecond\n");
String text = Files.readString(file);
List<String> lines = Files.readAllLines(file);
System.out.println(text.length());
System.out.println(lines.size());
}
}Exercise
Does Path.of("missing.txt") fail immediately if the file does not exist?
Show answer
No. It creates a path description. A file operation such as Files.readString discovers whether the file exists.