Java IO 採用裝飾器模式設計,四大抽象基類 InputStream/OutputStream (字節) 與 Reader/Writer (字符) 構建了靈活的流體系。本文系統梳理核心流類別、關鍵方法、典型應用場景與代碼範例。
| 維度 | 字節流 | 字符流 |
|---|---|---|
| 基本單位 | Byte (8 bits) | Char (16 bits, UTF-16) |
| 編碼處理 | 無,直接讀寫位元組 | 內建編碼轉換,依賴 Charset |
| 適用資料 | 所有二進位資料 (圖片、影音、壓縮包) | 純文本資料 |
| 中文處理 | UTF-8 佔 3 位元組,GBK 佔 2 位元組 | 自動對應字符,無需手動處理 |
| 選型原則 | 非文本、或不確定編碼時 | 純文本處理優先 |
// InputStream
int read() // 讀單位元組,回傳 int (0-255 或 -1 表 EOF)
int read(byte[] b) // 批次讀入位元組陣列
int read(byte[] b, int off, int len) // 指定偏移與長度讀取
// OutputStream
void write(int b) // 寫單位元組 (低 8 位)
void write(byte[] b) // 寫位元組陣列
void write(byte[] b, int off, int len) // 寫部分陣列
void flush() // 強制刷新緩衝區
// 複製檔案範例 (1KB 緩衝)
try (InputStream in = new FileInputStream("src.txt");
OutputStream out = new FileOutputStream("dest.txt")) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
mark()/reset() 標記重讀 (僅輸入流)try (InputStream in = new BufferedInputStream(new FileInputStream("src.txt"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("dest.txt"))) {
// 同樣代碼,效能指數級提升
}
Serializable (標記介面,無方法)writeObject()/readObject() 自動處理物件圖transient 關鍵字排除不需序列化欄位// 寫入
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"))) {
oos.writeObject(new Student("張三", 18));
oos.writeObject(new Student("李四", 20));
}
// 讀取 (須按寫入順序)
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.dat"))) {
System.out.println(ois.readObject()); // Student[name=張三,age=18]
System.out.println(ois.readObject()); // Student[name=李四,age=20]
}
readInt()/writeInt()、readUTF()/writeUTF() 等InputStreamReader 指定編碼char[]) 替代位元組陣列readLine() 按行讀取 (自動處理 \n, \r, \r\n)newLine() 寫入平台相關換行符 (優於硬編碼 \n)try (BufferedReader br = new BufferedReader(new FileReader("src.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("dest.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine(); // 跨平台換行
}
}
new InputStreamReader(new FileInputStream(file), "UTF-8")try (InputStreamReader isr = new InputStreamReader(new FileInputStream("src.txt"), "UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("dest.txt"), "UTF-8")) {
char[] buf = new char[1024];
int len;
while ((len = isr.read(buf)) > 0) {
osw.write(buf, 0, len);
}
}
| 場景 | 推薦流組合 |
|---|---|
| 複製二進位檔案 (圖片/影片) | BufferedInputStream → BufferedOutputStream |
| 讀寫純文本檔案 | BufferedReader → BufferedWriter |
| 指定編碼讀寫文本 | InputStreamReader(編碼) → OutputStreamWriter(編碼) |
| 物件持久化/網路傳輸 | ObjectOutputStream → ObjectInputStream |
| 結構化基本型別資料 | DataOutputStream → DataInputStream |
| 大檔案隨機存取 | RandomAccessFile (rw 模式) |
Java IO 是裝飾器模式教科書級應用:
FileInputStream) 提供基礎 I/O 能力BufferedInputStream, DataInputStream) 包裝節點流,動態增加功能new DataInputStream(new BufferedInputStream(new FileInputStream(f)))InputStream,輸出流繼承 OutputStream掌握 IO 體系精髓:節點流接源頭,處理流加功能,裝飾器靈活組合,編碼轉換靠橋樑。