Java 21 File I/O, NIO.2 Paths, and Serialization
Introduction
Java 21 file I/O connects streams, NIO.2 paths, file operations, and object serialization. These skills belong to the Using Java I/O API topic in preparation for Oracle Java SE 21 Developer (1Z0-830). Learn to predict path results, handle failures, and trace restored object state.
To keep the lesson concrete, we work on a small invoicing tool for a bookshop: it reads a CSV of orders, writes a report, stores invoice objects on disk, and archives old files. Every example below belongs to that tool. Absolute-path examples assume the default Unix-like provider, with / as the root and separator; Windows and other providers can differ. Snippets assume the relevant java.io, java.nio.file, java.nio.charset, java.util, and stream imports, with checked exceptions handled or declared by the surrounding method.
Learning objectives
After this lesson you will be able to:
- Use byte streams (
InputStream,OutputStream) and character streams (Reader,Writer) with buffering, and choose between them. - Read from and write to the console with
System.in,System.outandjava.io.Console. - Read and write text and binary files with
Files,BufferedReader,BufferedWriter,PrintWriter. - Create, resolve, relativize, normalize and compare
Pathobjects. - Copy, move, delete, list and walk files and directories with
Files, with the rightStandardCopyOptionandOpenOptionvalues. - Read file attributes.
- Serialize and deserialize objects, and explain the effect of
Serializable,transient,staticandserialVersionUID.
1. Streams: bytes and characters
java.io has two families.
| Family | Base classes | Unit | Typical subclasses |
|---|---|---|---|
| Byte streams | InputStream, OutputStream |
int (0 to 255) / byte |
FileInputStream, FileOutputStream, ByteArrayInputStream, BufferedInputStream, DataInputStream, ObjectInputStream |
| Character streams | Reader, Writer |
char |
FileReader, FileWriter, BufferedReader, BufferedWriter, InputStreamReader, PrintWriter, StringReader |
InputStream.read() returns an int in the range 0 to 255, or -1 at end of stream. read(byte[]) may return fewer bytes than the buffer can hold; it returns -1 at end of stream, or 0 for a zero-length buffer. Bridges between the families are InputStreamReader and OutputStreamWriter, which take a charset.
Wrappers add features (decorator pattern):
try (BufferedReader in = Files.newBufferedReader(Path.of("orders.csv"), StandardCharsets.UTF_8);
BufferedWriter out = Files.newBufferedWriter(Path.of("report.txt"), StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) { // null at end of file
out.write(line.toUpperCase(Locale.ROOT));
out.newLine();
}
} // closes both, in reverse orderFor related reasoning, review Java exception handling and try-with-resources.
Rules:
- Closing a wrapper closes the wrapped stream. With try-with-resources, resources close in reverse order of declaration.
BufferedWritercontent may remain buffered untilflush()orclose(). These pass data onward; they do not guarantee durable storage on physical disk. Failing to close can lose buffered data.FileWritertruncates the file by default;new FileWriter(name, true)appends.FileOutputStreambehaves the same way with its second argument.readLine()removes the line terminator and returnsnullat the end.- Writing methods of
PrintWriterandPrintStreamsuppressIOExceptionand set an error flag checked withcheckError(). Their file-opening constructors can still throw checked exceptions. The example usesBufferedWriterso write failures propagate. FileReaderandFileWriteruse the default charset (UTF-8 by default since Java 18, JEP 400). Always prefer an explicit charset:new FileReader(file, StandardCharsets.UTF_8).DataOutputStreamwrites primitives in binary (writeInt,writeUTF), andDataInputStreammust read them back in the same order.mark(int)/reset()work only whenmarkSupported()is true (for exampleBufferedReader,ByteArrayInputStream).
2. Console I/O
System.in is an InputStream, System.out and System.err are PrintStreams. A Scanner or BufferedReader makes keyboard input comfortable:
Scanner sc = new Scanner(System.in);
int qty = sc.nextInt();
sc.nextLine(); // consume the rest of the line
String note = sc.nextLine();A classic bug: nextInt() does not consume the line terminator, so the next nextLine() reads the rest of that line, which is empty if only the terminator remains. Closing a scanner also closes its input; avoid closing a shared System.in prematurely.
java.io.Console is obtained with System.console(). In Java 21 availability depends on the platform and JVM launch; IDE consoles and redirected execution commonly yield null. Its methods include readLine(), readPassword() (a non-echoed char[]), printf and writer(). Check for null, and clear password arrays with Arrays.fill(password, '\0') after use.
3. Files with java.nio.file
The NIO.2 API (Java 7) is the modern way. Its core types are the interface Path, the utility class Files and the helper Paths (or Path.of, preferred since Java 11).
Creating and inspecting paths
Path p = Path.of("/shop/data/../invoices/2026/inv-001.txt");
p.getFileName(); // inv-001.txt
p.getParent(); // /shop/data/../invoices/2026
p.getRoot(); // /
p.getNameCount(); // 6 (shop, data, .., invoices, 2026, inv-001.txt)
p.getName(0); // shop
p.subpath(1, 3); // data/..
p.isAbsolute(); // true
p.normalize(); // /shop/invoices/2026/inv-001.txtName inspection, resolve, relativize, and normalize manipulate path representations without checking existence. This is not true of every Path method: toRealPath() accesses the file system. Files.exists(path) and Files.notExists(path) do. Note that both can be false (when access is denied or status is unknown).
resolve, relativize, normalize, toAbsolutePath
| Method | Behavior | Example result |
|---|---|---|
a.resolve(b) |
Appends b to a; if b is absolute, returns b |
/shop.resolve(inv/1.txt) = /shop/inv/1.txt |
a.resolveSibling(b) |
Resolves b against a.getParent() |
/shop/a.txt.resolveSibling(b.txt) = /shop/b.txt |
a.relativize(b) |
Path from a to b; both must be absolute or both relative; roots and provider rules must also be compatible, otherwise IllegalArgumentException |
/shop.relativize(/shop/inv/1.txt) = inv/1.txt |
p.normalize() |
Removes . and resolves .. lexically |
a/b/../c becomes a/c |
p.toAbsolutePath() |
Prepends the working directory if relative | |
p.toRealPath() |
Resolves symbolic links, checks existence, throws IOException if absent |
relativize with ..: Path.of("/a/b").relativize(Path.of("/a/c/d")) is ../c/d. Path.of("a").resolve("") returns a. normalize does not touch the file system, so on a symbolic link it can differ from the real parent.
Reading and writing whole files
Path orders = Path.of("data", "orders.csv");
List<String> lines = Files.readAllLines(orders); // UTF-8
String text = Files.readString(orders); // Java 11
byte[] bytes = Files.readAllBytes(orders);
try (Stream<String> s = Files.lines(orders)) { // lazy, must be closed
long big = s.filter(l -> l.endsWith(",PAID")).count();
}
Files.writeString(Path.of("report.txt"), "Total: 42\n");
Files.write(Path.of("report.txt"), List.of("a", "b"), StandardOpenOption.APPEND);
try (BufferedWriter w = Files.newBufferedWriter(Path.of("out.txt"))) {
w.write("hello");
w.newLine();
}Files.write and writeString default to CREATE, TRUNCATE_EXISTING and WRITE. With APPEND, the file is extended. With CREATE_NEW, an existing file causes FileAlreadyExistsException. Opening a missing file for reading throws NoSuchFileException. All of these are subclasses of IOException.
Create, copy, move, delete
Files.createDirectory(Path.of("archive")); // parent must exist
Files.createDirectories(Path.of("archive/2026/10")); // creates missing parents; an existing directory is OK
Files.createFile(Path.of("archive/readme.txt")); // FileAlreadyExistsException if present
Files.copy(src, dst); // fails for a distinct existing target without REPLACE_EXISTING
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
Files.delete(path); // NoSuchFileException if absent, DirectoryNotEmptyException if non-empty directory
Files.deleteIfExists(path); // returns booleanImportant details:
Files.copyof a directory copies only the directory itself, not its content (an empty directory is created). Copy is shallow.- Attribute copying without
COPY_ATTRIBUTESis limited and provider-dependent. The option requests supported attributes but does not promise preservation of every attribute. Copying a file onto itself is a special case that can do nothing. - A directory move can be a rename when the provider supports it. With
ATOMIC_MOVE, other options are ignored, existing-target replacement is implementation-specific, and unsupported atomic moves throwAtomicMoveNotSupportedException, for example across file stores. AddingREPLACE_EXISTINGdoes not promise atomic replacement. createDirectoriesaccepts existing directories, not an ordinary file at a required directory path. Failure may leave some parents already created.- There is also
Files.copy(InputStream, Path)andFiles.copy(Path, OutputStream).
Listing and walking
| Method | Depth | Returns | Notes |
|---|---|---|---|
Files.list(dir) |
One level | Stream<Path> |
Must be closed |
Files.walk(dir) |
Recursive (all) | Stream<Path> |
Includes dir itself; walk(dir, maxDepth) limits depth |
Files.find(dir, depth, BiPredicate) |
Recursive | Stream<Path> |
Predicate receives path and attributes |
Files.newDirectoryStream(dir, glob) |
One level | DirectoryStream<Path> |
Glob filter, closeable |
Files.walkFileTree(dir, visitor) |
Recursive | Visitor callbacks, used for recursive delete |
try (Stream<Path> s = Files.walk(Path.of("archive"), 2)) {
s.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".txt"))
.forEach(System.out::println);
}By default, walk does not follow symbolic links to directories. Errors during lazy traversal can surface as UncheckedIOException, after the initial call.
For related reasoning, review Java streams and lambda expressions.
Walking depth: walk(dir, 1) is equivalent to list(dir) plus dir itself. A recursive delete of a tree needs walkFileTree or a reverse-sorted walk, because Files.delete refuses non-empty directories.
Attributes
long size = Files.size(path);
boolean dir = Files.isDirectory(path);
FileTime modified = Files.getLastModifiedTime(path);
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
attrs.creationTime(); attrs.isSymbolicLink();
Files.isSameFile(a, b); // compares the actual files, can throw IOException
Files.isReadable(path); Files.isWritable(path); Files.isHidden(path);Path equality: Path.of("a").equals(Path.of("a/")) is true (trailing separator is removed), but Path.of("a/../b") is not equal to Path.of("b"), since equality is syntactic.
4. Legacy java.io.File
File still appears. new File("x") does nothing on disk. exists(), mkdir(), mkdirs(), and delete() report results with booleans, although security failures may throw. createNewFile() also returns a boolean and declares IOException. list() returns a String[] or null if listing fails or the path is not a directory. toPath() bridges to NIO; Path.toFile() supports the default file system and may reject other providers. New code should prefer Path and its more informative failures.
5. Serialization
Serialization converts an object graph into a byte stream with ObjectOutputStream.writeObject; ObjectInputStream.readObject reconstructs it. For ordinary default serialization, every non-null object reached through a non-transient instance field must be serializable; otherwise writing fails with NotSerializableException. The declared field type alone does not determine the outcome: its value may be null or a serializable implementation.
record Customer(String name) implements Serializable { }
class Invoice implements Serializable {
private static final long serialVersionUID = 1L;
private String number;
private transient String internalNote; // not serialized
private static int counter = 99; // not serialized (belongs to the class)
private Customer customer = new Customer("Maya"); // reachable serializable value
Invoice(String number, String note) { this.number = number; this.internalNote = note; }
}
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(Path.of("inv.ser")))) {
out.writeObject(new Invoice("INV-1", "secret"));
}
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(Path.of("inv.ser")))) {
Invoice copy = (Invoice) in.readObject(); // ClassNotFoundException, IOException
// copy.internalNote == null
}Rules to memorize:
- Constructors: for ordinary serializable classes, the constructor of the serializable class (and of serializable ancestors) is not called. The no-argument constructor of the first non-serializable superclass is called, so that class must have an accessible no-argument constructor, otherwise
InvalidClassExceptionoccurs at read time. - Default values: with ordinary default serialization and no restoration hook,
transientfields come back as their default (null,0,false), not the initializer value from the declaration (initializers do not run either, since the constructor is skipped). - Static fields are not part of the object state.
- Object graph: non-null objects reached through non-transient instance fields must be serializable under default serialization; encountering a non-serializable object during writing causes
NotSerializableException. - serialVersionUID: a
longconstant used to check compatibility. If absent, the JVM computes one from the class structure, so structural changes can alter it. A mismatch causesInvalidClassException. Declare it explicitly, but a matching value does not make every class evolution compatible. - Inheritance: if the superclass is serializable, so are all subclasses. Fields of a non-serializable superclass are not saved.
- Shared references in ordinary object graphs are preserved within one stream: if two fields point at the same object, they point to one copy after reading.
- Records can be serializable by implementing
Serializable; their state is rebuilt through the canonical constructor, andserialVersionUIDis not compared for them. - Custom hooks
private void writeObject(ObjectOutputStream)andprivate void readObject(ObjectInputStream)allow custom handling;Externalizablerequires a public no-argument constructor. - Never deserialize untrusted data; use
ObjectInputFilterif you must.
Worked example: round trip with transient and static
Statement. Given the class below, what does the program print?
class Book implements Serializable {
String title;
transient int copies = 5;
static String shelf = "A";
Book(String t, int c) { title = t; copies = c; }
}
// Inside a method declaring IOException and ClassNotFoundException:
Book b = new Book("Java 21", 12);
Book.shelf = "B";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
out.writeObject(b);
}
Book.shelf = "C";
Book r;
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()))) {
r = (Book) in.readObject();
}
System.out.println(r.title + " " + r.copies + " " + Book.shelf);Step 1. title is a normal instance field: it is written and restored as Java 21.
Step 2. copies is transient, so it is not written. On reading, the constructor is not called and the declaration initializer = 5 does not run, so the field gets the default 0.
Step 3. shelf is static, so it is not in the stream. It keeps the current JVM value, C.
Solution. The output is Java 21 0 C.
Why the other choices are wrong. Java 21 12 C forgets transient. Java 21 5 C assumes the initializer runs, which only happens when a constructor is called. Java 21 0 B assumes static state is saved at serialization time.
Second worked example: path arithmetic
Statement. On the default Unix-like provider, what do these lines print?
Path base = Path.of("/shop/reports");
Path archived = Path.of("/shop/archive/2026/q3.csv");
Path file = Path.of("/shop/archive/../reports/2026/q3.csv");
System.out.println(base.relativize(archived));
System.out.println(base.relativize(file.normalize()));
System.out.println(file.normalize().getNameCount());Step 1. The first pair has no redundant dot segments. From /shop/reports, climb to /shop and descend into archive/2026/q3.csv: ../archive/2026/q3.csv.
Step 2. Explicitly normalize the second target to /shop/reports/2026/q3.csv. Relative to base, this is 2026/q3.csv.
Step 3. The normalized target has four names: shop, reports, 2026, and q3.csv; the root is not a name.
Solution. The lines print ../archive/2026/q3.csv, 2026/q3.csv, and 4.
Why other answers are wrong. Do not infer a portable rule that relativize retains every raw .. segment: provider implementations can normalize while computing a relative path. Normalize explicitly when that is the intended comparison. Counting the root incorrectly gives five names.
Common pitfalls and exam tips
- Exam tip: distinguish lexical path operations from operations that inspect the file system;
Path.toRealPath()is itself an I/O operation. Files.lines,list,walkandfindreturn streams that hold open handles: use try-with-resources.resolvewith an absolute argument returns the argument.relativizeneeds two paths of the same kind.- Copying onto a distinct existing target normally fails without
REPLACE_EXISTING; specific exception types can depend on the provider.deleteIfExistsreturnsfalsefor a missing entry but can still throw for other failures. - Copying a directory copies no content; deleting a non-empty directory fails with
DirectoryNotEmptyException. FileWritertruncates unless the append flag istrue.- Forgetting to close a buffered writer can lose buffered data.
- Default serialization omits
transientandstaticfields; ordinary serializable-class constructors are skipped. Records use their canonical constructor. - A reachable non-serializable field value can fail at write time; the declared type alone does not prove failure.
System.console()can benull.
Mini case study: archiving old invoices
Scenario. The bookshop keeps invoices as .txt files under /shop/invoices/YYYY/MM/. Once a month, invoices older than the current year must be moved to /shop/archive/YYYY/ keeping the sub-folder layout, and a manifest file listing the moved files and their sizes must be written. Invoice objects are also cached on disk as .ser files.
Questions. (1) Which API walks the tree? (2) How do you compute each target path? (3) What happens on a second run, and how do you make the move safe? (4) What is wrong with caching a Customer object that holds a Connection field?
Solution.
- Use
Files.walk(root)inside try-with-resources. Select regular.txtfiles, then inspect the relative path's first element as a four-digit year. Keep only years less thanLocalDate.now(clock).getYear(), using an explicitly chosen business clock and zone. Report malformed year directories. Collect selected paths before moving them. - Compute
Path rel = root.relativize(source)andPath target = archiveRoot.resolve(rel). This preservesYYYY/MM/file.txtbelow the archive root. Create target parents withFiles.createDirectories; capturelong size = Files.size(source)before moving. - Move without replacement to protect existing archives. Report collisions and other failures. Append only successful moves to a UTF-8 manifest with relative path and captured size, using
CREATEandAPPEND. Successfully moved sources disappear, but failed or newly arrived eligible files may remain for another run. Moving and writing the manifest are separate operations: a crash between them requires reconciliation. Neither appending nor an atomic file move makes the entire workflow transactional. - A live connection implementation is generally unsuitable for serialization. A non-null, non-serializable implementation reached through a non-transient field causes
NotSerializableException; theConnectioninterface type alone is not proof. Exclude infrastructure state, or mark ittransientand reconnect after reading.
Key terms
- Byte stream / character stream: classes that read or write raw bytes / text characters.
- Decorator (wrapper): a stream that adds buffering or conversion around another stream.
- Path: an immutable, file-system-aware representation of a location, which may not exist.
- Files: the utility class with static methods that perform file operations.
- Normalize: remove redundant
.and..elements lexically. - Serialization: converting an object graph to bytes with
ObjectOutputStream. - transient: modifier that excludes an instance field from default serialization.
- serialVersionUID: the version identifier checked when deserializing.
Summary checklist
- I can choose between byte and character streams and wrap them with buffers.
- I know
read()returns -1 at the end andreadLine()returnsnull. - I can read and write files with
Filesand know the default open options. - I can predict results of
resolve,relativize,normalize,getNameCount,subpath. - I know the exceptions of
copy,move,deleteandcreateFile. - I know
list,walkandfindreturn streams that must be closed. - I can predict what is restored after deserialization (
transient,static, constructors). - I know the role of
serialVersionUIDandNotSerializableException.
Official sources
- Oracle exam page 1Z0-830 (objectives): https://education.oracle.com/java-se-21-developer-professional/pexam_1Z0-830 (opens in a new tab)
java.nio.filepackage: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/package-summary.html (opens in a new tab)FilesAPI: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Files.html (opens in a new tab)PathAPI: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Path.html (opens in a new tab)java.iopackage: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/package-summary.html (opens in a new tab)- Java Object Serialization Specification: https://docs.oracle.com/en/java/javase/21/docs/specs/serialization/index.html (opens in a new tab)
- Official Java SE 21 learning path: https://learn.oracle.com/ols/learning-path/become-a-java-se-21-developer/117252/138845 (opens in a new tab)
PrintWritererror handling: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/PrintWriter.html (opens in a new tab)FileAPI: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/io/File.html (opens in a new tab)- JEP 400, UTF-8 by default: https://openjdk.org/jeps/400 (opens in a new tab)
