Java IO 是處理數據傳輸的核心 API,涵蓋文件、網絡、內存等數據源。本文梳理流體系架構、核心類層次、裝飾器模式應用及 NIO/AIO 現代化演進。
| 維度 | 字節流 | 字符流 |
|---|---|---|
| 最小單位 | Byte (8bit) | Char (16bit UTF-16) |
| 基類 | InputStream / OutputStream | Reader / Writer |
| 典型場景 | 圖片、視頻、二進制協議 | 文本文件、JSON、XML、網頁 |
| 轉換橋樑 | InputStreamReader / OutputStreamWriter (指定 Charset) | |
InputStream (abstract)
├── FileInputStream // 文件讀取
├── ByteArrayInputStream // 內存緩衝區讀取
├── FilterInputStream // 裝飾器基類
│ ├── BufferedInputStream // 緩衝讀取(提升性能)
│ ├── DataInputStream // 基本類型讀取
│ └── ObjectInputStream // 對象反序列化
└── PipedInputStream // 線程間管道
OutputStream 同理對稱
Reader/Writer 體系結構類似,處理字符編碼轉換
Java IO 大量使用裝飾器動態組合功能:
// 經典組合:文件 → 緩衝 → 對象反序列化
ObjectInputStream ois = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream("user.dat")));
// 文本讀取:文件 → 緩衝字符 → 按行讀取
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("log.txt"), StandardCharsets.UTF_8));
StandardCharsets.UTF_8,避免平台默認編碼差異。BufferedInputStream/BufferedReader,減少系統調用次數。readAllBytes(),改用流式處理或 mmap (FileChannel.map)。// Path / Files 工具類
Path path = Paths.get("/data/log.txt");
List lines = Files.readAllLines(path, StandardCharsets.UTF_8); // 小文件
Files.write(path, "new line".getBytes(), StandardOpenOption.APPEND);
// Channel + Buffer (高性能非阻塞基礎)
FileChannel channel = FileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(8192);
while (channel.read(buffer) > 0) {
buffer.flip();
// 處理數據
buffer.clear();
}
// 異步 IO (Java 7 AIO)
AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path);
Future future = asyncChannel.read(buffer, 0);
// 或回調 CompletionHandler
掌握「字節/字符雙體系、裝飾器組合、緩衝優先、NIO 非阻塞」四大核心,即可應對 95% IO 開發場景。建議配合 java.nio.file.Files 工具類簡化常規操作,性能敏感處再深入 Channel/Buffer。