首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java IO 體系深度解析:字節流、字符流、緩衝流、轉換流、物件流、資料流完整指南

     編輯:Java 綜合教學

Java IO 體系深度解析:字節流、字符流、緩衝流、轉換流、物件流、資料流完整指南

Java IO 採用裝飾器模式設計,四大抽象基類 InputStream/OutputStream (字節) 與 Reader/Writer (字符) 構建了靈活的流體系。本文系統梳理核心流類別、關鍵方法、典型應用場景與代碼範例。

核心區別:字節流 vs 字符流

維度字節流字符流
基本單位Byte (8 bits)Char (16 bits, UTF-16)
編碼處理無,直接讀寫位元組內建編碼轉換,依賴 Charset
適用資料所有二進位資料 (圖片、影音、壓縮包)純文本資料
中文處理UTF-8 佔 3 位元組,GBK 佔 2 位元組自動對應字符,無需手動處理
選型原則非文本、或不確定編碼時純文本處理優先

一、字節流體系

1. 基礎抽象類關鍵方法

// 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()                  // 強制刷新緩衝區

2. FileInputStream / FileOutputStream — 檔案節點流

// 複製檔案範例 (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);
    }
}

3. BufferedInputStream / BufferedOutputStream — 緩衝裝飾流

  • 內建 8KB 預設緩衝區,減少系統呼叫次數,大幅提升效能
  • 支援 mark()/reset() 標記重讀 (僅輸入流)
  • 本質:裝飾器模式包裝節點流
try (InputStream in = new BufferedInputStream(new FileInputStream("src.txt"));
     OutputStream out = new BufferedOutputStream(new FileOutputStream("dest.txt"))) {
    // 同樣代碼,效能指數級提升
}

4. ObjectInputStream / ObjectOutputStream — 物件序列化流

  • 要求類實作 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]
}

5. DataInputStream / DataOutputStream — 資料類型流

  • 按基本型別讀寫:readInt()/writeInt()、readUTF()/writeUTF() 等
  • 解決「讀到哪裡停」的邊界問題,適合結構化資料儲存

二、字符流體系

1. FileReader / FileWriter — 字符檔案節點流

  • 預設使用平台預設編碼 (如 UTF-8),可透過 InputStreamReader 指定編碼
  • 字符陣列緩衝 (char[]) 替代位元組陣列

2. BufferedReader / BufferedWriter — 字符緩衝流

  • 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(); // 跨平台換行
    }
}

3. InputStreamReader / OutputStreamWriter — 字節轉字符橋樑

  • 核心作用:指定編碼 (如 UTF-8, GBK) 進行字節↔字符轉換
  • 解決中文亂碼關鍵: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 體系精髓:節點流接源頭,處理流加功能,裝飾器靈活組合,編碼轉換靠橋樑。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved