I/O, NIO.2, and Serialization
Domain 7 tests the java.io stream hierarchy, the java.nio.file path API, and the serialization contract: which classes are byte- versus character-oriented, and what makes an object serializable.
I/O streams
- Byte streams (
InputStream/OutputStream) handle binary data; character streams (Reader/Writer) handle text with a charset. BufferedReader.readLine()returnsnullat end of stream;InputStream.read()returns-1. Always close with try-with-resources.Fileis the legacy API;PathplusFilesreplaces it.
NIO.2
Path.of("a", "b")(orPaths.get) builds a path;resolveappends,relativizecomputes the difference between two paths, andnormalizeremoves.and..textually without touching the disk.Files.exists,isDirectory,createDirectories,copy,move,delete,readAllLines,lines,walk,list.Files.walkandFiles.listreturn lazyStream<Path>objects that must be closed.
Serialization
- A class must implement the marker interface
java.io.Serializable; non-transient, non-static fields are written. transientfields are skipped and restored to default values. AserialVersionUIDmismatch throwsInvalidClassException.- A non-serializable field throws
NotSerializableExceptionunless it istransient. - During deserialization, constructors of serializable classes do not run; the no-arg constructor of the first non-serializable superclass does.
Worked example
try (var out = new ObjectOutputStream(new FileOutputStream("d.bin"))) {
out.writeObject(new Point(1, 2));
}
Point must implement Serializable; otherwise writeObject throws NotSerializableException at runtime, and the file may already contain partial bytes.
Traps
Files.deletethrowsNoSuchFileException;deleteIfExistsreturns a boolean.Files.copyfails if the target exists unlessREPLACE_EXISTINGis passed.- Closing only the outer wrapper closes the entire chain.