IO (Input/Output) 是程式與外部世界 (檔案、網路、控制台) 交換資料的介面。Java 核心庫 java.io 以 流 (Stream) 為核心抽象:資料被序列化為位元組序列寫入輸出流,或從輸入流讀取並反序列化。這種「水管」模型簡單直觀,但因逐位元組處理,效率受限於頻繁的系統呼叫與記憶體拷貝。
| 維度 | 位元組流 (XxxStream) | 字元流 (XxxReader/Writer) |
|---|---|---|
| 處理單位 | Byte (8 bits) | Char (16 bits, UTF-16) |
| 適用場景 | 圖片、聲音、二進位檔、網路傳輸 | 文字檔、XML、JSON、含中文的文本 |
| 編碼轉換 | 需自行處理 | 內建編碼/解碼器 (Charset) |
| 基類 | InputStream / OutputStream | Reader / Writer |
橋接樁:InputStreamReader / OutputStreamWriter 可在兩者間轉換,指定 Charset (如 UTF-8) 即可正確處理中文。
Java IO 傳統體系是 Decorator Pattern 教科書級應用:
InputStream / OutputStream (抽象介面)FileInputStream, ByteArrayInputStream (資料源頭/終點)FilterInputStream / FilterOutputStream (功能增強基類)BufferedInputStream (緩衝), DataInputStream (基本型別讀取), GZIPInputStream (壓縮)…組裝範例:new BufferedInputStream(new FileInputStream("log.txt")) —— 先接檔案源頭,再疊加緩衝功能,靈活組合、動態擴充。
JDK 1.4 引入 java.nio,核心抽象轉向 Channel (通道) 與 Buffer (緩衝區):
ByteBuffer.allocateDirect() 分配堆外記憶體,避免 GC 壓力,配合 OS 零拷貝 (Zero-copy) 效能極致。Selector + SelectableChannel 實現單執行緒管理成千上萬連結,是 Netty、Undertow 等高效能網路框架的基石。MappedByteBuffer 將檔案直接映射至進程位址空間,隨機存取極快。try (InputStream in = new BufferedInputStream(new FileInputStream("src.dat"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("dst.dat"))) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
try (FileChannel in = FileChannel.open(Paths.get("src.dat"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("dst.dat"),
StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
// 零拷貝:直接在核心空間傳輸,不經用戶空間
long transferred = in.transferTo(0, in.size(), out);
}
java.nio.file.Files 靜態工具類 (Files.copy(), Files.readAllLines() 等),API 簡潔且底層自動優化。