Sub topic 3
Handling I/O Errors
Assume you know basic Java, Path, Files, checked exceptions, and try-with-resources. Java file operations can fail because a path is missing, permissions changed, or another process locks a file. Most methods in Files report these failures with IOException.
Handling I/O errors
Catch specific subclasses before the general exception:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class FileErrors {
public static void main(String[] args) {
try {
System.out.println(Files.readString(Path.of("missing.txt")));
} catch (NoSuchFileException e) {
System.out.println("Missing: " + e.getFile());
} catch (IOException e) {
System.out.println("I/O failure: " + e.getMessage());
}
}
}Do not silently ignore an IOException. Either handle it, or declare it with throws IOException when the caller can respond appropriately.
Checking attributes and managing directories
Files.exists checks whether a path currently exists. Files.isRegularFile and Files.isDirectory distinguish common path types. These checks can become outdated immediately, so still handle exceptions when performing the operation.
Files.size(path) reads the file size. Other methods such as Files.getLastModifiedTime read metadata.
Use createDirectories for a directory and all missing parents. Files.list returns a stream that must be closed.
Path folder = Path.of("data", "reports");
Files.createDirectories(folder);
try (var entries = Files.list(folder)) {
entries.forEach(System.out::println);
}Copying, moving, and deleting
Files.copy duplicates data. Files.move renames or relocates it. Files.deleteIfExists avoids an error when the target is already absent. Options such as REPLACE_EXISTING control replacement behavior.
Walking directory trees
Files.walk visits descendants as a stream. Filter before processing, and close the stream.
try (var paths = Files.walk(Path.of("."))) {
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".txt"))
.forEach(System.out::println);
}Writing safely
Writing directly to a target can leave a partial file after a failure. Write a temporary file in the target directory, then move it into place. ATOMIC_MOVE requests a filesystem-level atomic replacement, but some filesystems do not support it.
Path target = Path.of("data/report.txt");
Files.createDirectories(target.getParent());
Path temp = Files.createTempFile(target.getParent(), "report-", ".tmp");
try {
Files.writeString(temp, "complete\n");
Files.move(temp, target, java.nio.file.StandardCopyOption.ATOMIC_MOVE,
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}Legacy `java.io.File`
File is the older path representation. Convert between APIs with file.toPath() and path.toFile(). Prefer Path and Files for new code.
Exercise
Why should a temporary file be created in the target directory?
Show answer
A move within one filesystem is more likely to support atomic replacement, and the operation avoids crossing filesystem boundaries.