Reference
File I/O & Serialization (`pkg9io`)
Runnable demos: `pkg9io`. Run any with java pkg9io/io1FileBasics.java.
The two stream families
1Bytes : InputStream / OutputStream -> binary data (images, any file)2Chars : Reader / Writer -> text (charset-aware)Wrap a base stream in a Buffered variant to batch syscalls and speed up I/O.
Class map
| Need | Legacy (java.io) | Modern (java.nio.file) |
|---|---|---|
| Path handle | File |
Path / Paths.get / Path.of |
| Read bytes | FileInputStream |
Files.readAllBytes |
| Write bytes | FileOutputStream |
Files.write |
| Read text | FileReader + BufferedReader |
Files.readString / readAllLines |
| Write text | FileWriter / PrintWriter |
Files.writeString |
| Stream lines | BufferedReader.lines() |
Files.lines() (lazy) |
Rule: prefer
java.nio.file(NIO.2) for new code — it is shorter, UTF-8 by default, and richer.
Files in this package
| # | File | Topic |
|---|---|---|
| 1 | io1FileBasics |
File: create, inspect, list, delete |
| 2 | io2ByteStreams |
byte streams, buffering, transferTo, readAllBytes |
| 3 | io3CharacterStreams |
Reader/Writer, line-by-line, PrintWriter |
| 4 | io4NioFilesAndPaths |
Path + Files (the recommended API) |
| 5 | io5Serialization |
Serializable, transient, object <-> bytes |
| 6 | io6TryWithResourcesAndScanner |
AutoCloseable, Scanner parsing |
Gotchas
- Always use try-with-resources — it closes and flushes, even on exceptions.
- Resources close in reverse declaration order; close errors become suppressed exceptions.
transientfields andstaticfields are not serialized.- Security: never deserialize untrusted bytes (RCE risk) — use JSON for external data.
- Specify a charset (
StandardCharsets.UTF_8) to avoid platform-default surprises.
Source named in this chapter
- io1FileBasicspkg9io/io1FileBasics.java