Java SE 11 Developer study materials
Java SE 11 Developer study resources

Java SE 11 Developer: Java I/O API

Java SE 11 Developer · Work through your exam, one topic at a time.

All guide sections

Java I/O API

The exam tests byte versus character streams, the NIO.2 Files API, and serialization mechanics.

Byte and character streams

InputStream and OutputStream handle bytes; Reader and Writer handle characters with a charset. FileReader/FileWriter use the platform default charset, which is a portability trap - prefer new InputStreamReader(in, StandardCharsets.UTF_8). Wrap file streams in buffered streams for performance. BufferedReader.readLine() returns null at end of stream, not an empty string. All of these are AutoCloseable.

NIO.2 and the Files utility

Path.of("dir","file.txt") (or Paths.get) builds a path; resolve appends, relativize produces the inverse, normalize removes . and ... Files offers readAllLines, readString, writeString, lines, list, walk, copy, move, delete, deleteIfExists, createDirectories and exists. Files.copy fails if the target exists unless you pass StandardCopyOption.REPLACE_EXISTING. Files.walk and Files.list return lazy streams that must be closed in try-with-resources. Deleting a non-empty directory throws DirectoryNotEmptyException.

Serialization

A class must implement Serializable; transient and static fields are skipped. A mismatched serialVersionUID makes deserialization throw InvalidClassException; a non-serializable field throws NotSerializableException at write time, not at compile time.

Worked example

To delete a directory tree: try (Stream<Path> s = Files.walk(root)) { s.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }. Reasoning: walk yields parents before children, so reverse order deletes children first and the directory is empty when its turn comes.

Traps

Relying on the default charset; forgetting to close a Files.walk stream; assuming Files.delete removes directories recursively; comparing Paths with == instead of equals or Files.isSameFile.