Paths and Files
What you will learn
A Path is a filesystem address, not an open file. Files contains operations that create, read, inspect and move objects at those addresses. Start with a directory owned by your program and known short fixtures.
- Construct and resolve paths without string concatenation.
- Create and inspect a bounded UTF-8 file.
- Enumerate a directory and choose an explicit ordering.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Run in a fresh lab-owned working directory. Examples create a unique child directory and delete fixed fixture names in finally. Symlink and atomic-move examples require corresponding filesystem support. The item helper validates leaf names; bounded reads at most max plus one byte.
Create and read a small file
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir, "a.txt"); Files.writeString(file, "café", StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); System.out.println(file.getFileName()); System.out.println(Files.readString(file, StandardCharsets.UTF_8)); System.out.println(Files.size(file)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
a.txtcafé5Four Unicode characters occupy five UTF-8 bytes. The outer finally deletes only known fixture names.
Address versus object
Path.of creates a path value without requiring an existing file. Resolve a relative child using resolve; an absolute argument replaces the base. normalize removes redundant path elements without checking the filesystem. getFileName and getParent describe components; the parent can be null. Paths use provider-specific syntax. A legacy File can be converted with toPath; prefer Path for new code.
Operations and attributes
Files.writeString encodes text and creates or truncates by default; CREATE_NEW rejects existing files. Files.readString is appropriate for a known small UTF-8 fixture, not an arbitrary upload. Files.size counts bytes, not characters. Read BasicFileAttributes with NOFOLLOW_LINKS to inspect a link itself. Existence checks can become stale, and false may also mean that existence cannot be determined. Handle the actual operation and its IOException.
Directory iteration
DirectoryStream lazily enumerates directory entries, supports one iterator, and must be closed. Its encounter order is not guaranteed. Collect only bounded entries, sort names when predictable presentation matters, and do not descend into unknown directories. A Files.list stream also owns a resource and must be closed.
Resolve and normalize without opening
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path relative = Path.of("draft", "..", "a.txt"); System.out.println(relative.normalize().equals(Path.of("a.txt"))); System.out.println(dir.resolve(relative).normalize().equals(dir.resolve("a.txt").normalize())); System.out.println(Files.exists(dir.resolve("a.txt"), LinkOption.NOFOLLOW_LINKS)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
truetruefalseNormalization is lexical; it does not create or inspect the file.
Directory listing in defined order
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Files.writeString(item(dir,"b.txt"), "B"); Files.writeString(item(dir,"a.txt"), "A"); Files.write(item(dir,"data.bin"), new byte[]{1}); List<String> names = new ArrayList<>(); try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.txt")) { for (Path entry : entries) names.add(entry.getFileName().toString()); } Collections.sort(names); System.out.println(names); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
[a.txt, b.txt]The glob excludes the binary fixture. Sorting makes output deterministic.
Inspect basic attributes
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"a.txt"); Files.writeString(file,"ABC"); var attrs = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); System.out.println(attrs.isRegularFile()); System.out.println(attrs.size()); System.out.println(attrs.isSymbolicLink()); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
true3falseAttributes describe the observed entry; they do not lock it against changes.
Common mistakes
Do not concatenate path components with a hard-coded slash, assume exists guarantees a subsequent open, or print an unordered directory listing as if it were sorted. Never pass unknown host paths into these examples.
Practice
Within the provided owned directory create a.txt with UTF-8 text book using CREATE_NEW. Print its file name and its size in bytes. Use the same fixed-name cleanup structure.
Expected output:
a.txt4Compare your answer with the manual practice criteria.
Official reading: Path · Files · DirectoryStream. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Paths and Files — knowledge check
Original filesystem and I/O questions. Java 21-compatible scope.
What does Path.of produce?
What does Files.size count?
What does CREATE_NEW do if the file exists?
How should directory output become deterministic?
What does NOFOLLOW_LINKS request for attributes?