I/O
28 — File I/O & NIO
Previous: 27 Design Patterns · Next: 29 Networking
▶️ pkg9io/io1FileBasics.java → io6TryWithResourcesAndScanner.java
Two stream families
1Bytes → InputStream / OutputStream (images, binary)2Chars → Reader / Writer (text, charset-aware)Modern code prefers NIO.2: Path, Files.
Quick reference
1// Read all text (modern)2String content = Files.readString(path, StandardCharsets.UTF_8);3 4// Write text5Files.writeString(path, "hello", StandardCharsets.UTF_8);6 7// Stream lines lazily8try (Stream<String> lines = Files.lines(path)) {9 lines.filter(l -> !l.isBlank()).forEach(System.out::println);10}11 12// Always use try-with-resources13try (var in = Files.newInputStream(path)) {14 byte[] data = in.readAllBytes();15}Class order in pkg9io
| # | File | Topic |
|---|---|---|
| 1 | io1FileBasics |
Legacy File API |
| 2 | io2ByteStreams |
Binary I/O |
| 3 | io3CharacterStreams |
Text I/O |
| 4 | io4NioFilesAndPaths |
Preferred NIO.2 API |
| 5 | io5Serialization |
Object ↔ bytes |
| 6 | io6TryWithResourcesAndScanner |
Auto-close, parsing |
Full guide → I/O · 11 I/O & Serialization
Next → 29 Networking
Source named in this chapter
- io1FileBasicspkg9io/io1FileBasics.java