Java IO 採用「節點流 + 處理流」分層,以 裝飾者模式 動態組合功能:

InputStream(位元組輸入) → FileInputStream, ByteArrayInputStream, PipedInputStreamReader(字元輸入) → InputStreamReader(位元組轉字元橋樑), FileReader, BufferedReader// 位元組緩衝 + 資料型別讀取
DataInputStream dis = new DataInputStream(
new BufferedInputStream(
new FileInputStream("data.bin")));
// 字元緩衝逐行讀取(推薦)
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("log.txt"), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) { ... }
}

OutputStream(位元組輸出) → FileOutputStream, ByteArrayOutputStream, PipedOutputStreamWriter(字元輸出) → OutputStreamWriter, FileWriter, BufferedWriter, PrintWriter// 字元緩衝 + 自動 flush + UTF-8
try (PrintWriter pw = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("out.txt"), StandardCharsets.UTF_8)), true)) {
pw.println("Hello World");
}
新專案優先考慮 java.nio.file.Files + Path:
Files.readAllLines(path, UTF_8) / Files.write(path, lines, UTF_8)Files.newBufferedReader(path, UTF_8) / Files.newBufferedWriter(path, UTF_8)Files.walk(path) / Files.find()Files.getLastModifiedTime(path), Files.setPosixFilePermissions()| 場景 | 推薦組合 | 備註 |
|---|---|---|
| 文字檔逐行讀取 | BufferedReader + InputStreamReader(UTF-8) | 取代 FileReader(無法指定編碼) |
| 二進位大檔複製 | FileChannel.transferTo/From | 零拷貝,最快 |
| 物件序列化 | ObjectOutputStream / ObjectInputStream | 注意 serialVersionUID |
| 高併發日誌寫入 | Log4j2/Logback AsyncAppender | 勿手寫 PrintWriter |
| 記憶體資料互轉 | ByteArrayInputStream / ByteArrayOutputStream | 單元測試常用 |
StandardCharsets.UTF_8,避免平台預設編碼差異。BufferedOutputStream/Writer,減少系統呼叫。熟悉 IO 體系繼承關係與裝飾組合,即可針對任何資料源選出最高效、最安全的讀寫策略。