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

Java I/O 流體系全景圖:從基礎分類到實戰代碼模板

     編輯:Java 相關知識

核心抽象:四大基類

流類型輸入基類輸出基類最小單位
位元組流InputStreamOutputStreambyte (8 bits)
字元流ReaderWriterchar (16 bits Unicode)

所有具體流類均繼承自這四個抽象類。Reader/Writer 是 JDK 1.1 引入,補充字元處理能力;兩者介面完全對稱(read()/write() 重載)。

兩大分類維度

1. 按功能:節點流 vs 過濾流(裝飾器模式)

  • 節點流:直接操作資料源/目的地(檔案、記憶體、網路)。如 FileInputStream、ByteArrayInputStream、PipedInputStream。
  • 過濾流:包裝其它流,增加功能(緩衝、轉碼、格式化、資料類型讀寫)。如 BufferedInputStream、DataInputStream、InputStreamReader。

實戰鐵律:幾乎不直接使用節點流,而是層層包裝:

// 典型:檔案 → 緩衝 → 字元轉換 → 行讀取
BufferedReader in = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("data.txt"), "UTF-8"));

2. 按資料來源:常用節點流對照表

來源/目的地位元組流字元流
檔案FileInputStream / FileOutputStreamFileReader / FileWriter
記憶體陣列ByteArrayInputStream / ByteArrayOutputStreamCharArrayReader / CharArrayWriter
字串—StringReader / StringWriter
管道(執行緒間)PipedInputStream / PipedOutputStreamPipedReader / PipedWriter

關鍵橋接器:位元組 ↔ 字元轉換


// 位元組流 → 字元流(解碼)
InputStreamReader isr = new InputStreamStream(inputStream, "UTF-8");

// 字元流 → 位元組流(編碼)
OutputStreamWriter osw = new OutputStreamWriter(outputStream, "UTF-8");

必須顯式指定 charset,避免平台預設編碼(Windows GBK、Linux UTF-8)導致亂碼。

實戰代碼模板庫

1. 緩衝讀取檔案(按行)

public static String readFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) sb.append(line).append('\n');
        return sb.toString();
    }
}

2. 格式化寫入檔案

public static void writeWithLineNumber(String src, String dest) throws IOException {
    try (BufferedReader br = new BufferedReader(new StringReader(src));
         PrintWriter pw = new PrintWriter(
             new BufferedWriter(new OutputStreamWriter(
                 new FileOutputStream(dest), StandardCharsets.UTF_8)))) {
        String line; int n = 1;
        while ((line = br.readLine()) != null) pw.println(n++ + ": " + line);
    }
}

3. 系統標準流重定向

PrintStream console = System.out;
try (PrintStream fileOut = new PrintStream(
        new BufferedOutputStream(new FileOutputStream("out.txt")), true, "UTF-8")) {
    System.setOut(fileOut);
    System.out.println("這行寫入檔案");
} finally {
    System.setOut(console); // 恢復
}

4. 物件序列化與反序列化

// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(
        new BufferedOutputStream(new FileOutputStream("obj.dat")))) {
    oos.writeObject(userObject);
}

// 反序列化
try (ObjectInputStream ois = new ObjectInputStream(
        new BufferedInputStream(new FileInputStream("obj.dat")))) {
    User u = (User) ois.readObject();
}

注意:實作 Serializable,敏感欄位用 transient 排除。序列化會遞歸包含引用物件圖,支援深拷貝。

5. RandomAccessFile:隨機存取

try (RandomAccessFile raf = new RandomAccessFile("data.dat", "rw")) {
    raf.seek(100); // 跳到位元組 100
    raf.writeDouble(3.14);
    raf.seek(100);
    double d = raf.readDouble();
}

大檔案隨機讀寫首選;現代替代方案:MappedByteBuffer (NIO 記憶體映射)。

效能優化清單

  • 務必加緩衝:BufferedInputStream/BufferedReader 減少系統呼叫。
  • 批量讀寫:使用 byte[]/char[] 緩衝區,避免單位元組/字元操作。
  • 指定編碼:避免預設編碼轉換開銷與亂碼風險。
  • NIO.2 升級:Files.readAllLines()、Files.newBufferedReader()、FileChannel 映射更高效。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved