Oracle Java SE 21 study materials
Oracle Java SE 21 study resources

Oracle Java SE 21: Using Java I/O API

Oracle Java SE 21 · Work through your exam, one topic at a time.

All guide sections

Using Java I/O API

Paths and Files

java.nio.file is the modern API: Path.of("dir", "a.txt") (or Paths.get), with resolve (join), relativize, normalize, toAbsolutePath, getFileName, getParent. Files provides convenience methods: readString, readAllLines, writeString, exists, isDirectory, createDirectories, copy, move, delete, deleteIfExists, list, walk, lines. Files.copy throws FileAlreadyExistsException unless you pass StandardCopyOption.REPLACE_EXISTING, and walk/list return streams that must be closed.

Streams vs readers

Byte streams: InputStream/OutputStream (FileInputStream, BufferedInputStream). Character streams: Reader/Writer (FileReader, BufferedReader, PrintWriter). FileReader uses the platform default charset; specify StandardCharsets.UTF_8 when it matters. readLine() returns null at end of file while read() returns -1. Wrap for buffering, and always use try-with-resources, which closes in reverse order.

Serialization

ObjectOutputStream/ObjectInputStream require Serializable; transient and static fields are not serialized; a mismatched serialVersionUID causes InvalidClassException; a non-serializable field throws NotSerializableException at write time. java.io.File still appears as legacy API.

Worked rule: decide bytes versus characters by the class-name suffix - ...Stream handles bytes, ...Reader/...Writer handles characters; bridge with InputStreamReader/OutputStreamWriter and an explicit charset.