萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java IO 系統全景解析:位元組流、字元流、裝飾模式、RandomAccessFile 實戰

一、流的兩大體系

體系基本抽象類別處理單位典型用途
位元組流InputStream / OutputStreamByte (8 bits)圖片、影音、二進位檔、網路傳輸
字元流Reader / WriterChar (16 bits UTF-16)文字檔、XML、JSON、CSV

二、核心節點流(直接對接資料源/目的地)

類型位元組流字元流
記憶體陣列ByteArrayInputStream / ByteArrayOutputStreamCharArrayReader / CharArrayWriter
字串StringBufferInputStream (已淘汰)StringReader / StringWriter
檔案FileInputStream / FileOutputStreamFileReader / FileWriter
管道(執行緒間)PipedInputStream / PipedOutputStreamPipedReader / PipedWriter
序列合併SequenceInputStream—

三、裝飾模式:為流增加功能

FilterInputStream / FilterOutputStream 及 FilterReader / FilterWriter 子類別包裝節點流,提供額外功能:

功能位元組流裝飾字元流裝飾
緩衝BufferedInputStream / BufferedOutputStreamBufferedReader / BufferedWriter
基本型別讀寫DataInputStream / DataOutputStream— (改用 DataInputStream 配合 InputStreamReader)
行號追蹤LineNumberInputStream (已淘汰)LineNumberReader
推回輸入PushbackInputStreamPushbackReader
格式化輸出PrintStreamPrintWriter

四、轉換橋樑

// 位元組流 → 字元流 (指定編碼)
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);

五、RandomAccessFile:隨機存取檔案

  • 模式:"r" (唯讀)、"rw" (讀寫)、"rws"/"rwd" (同步寫入)。
  • 關鍵方法:seek(long pos) 移動檔案指標、getFilePointer() 取得當前位置、length() 檔案長度。
  • 適用場景:大檔案斷點續傳、索引檔案、記憶體映射替代方案。

六、綜合實戰範例

public class IODemo {
    public static void main(String[] args) throws IOException {
        // 1. 緩衝逐行讀取檔案
        try (BufferedReader in = new BufferedReader(new FileReader("src/IODemo.java"))) {
            String line;
            while ((line = in.readLine()) != null) System.out.println(line);
        }

        // 2. 從字串讀取
        String data = "Hello\nWorld";
        try (StringReader sr = new StringReader(data)) {
            int c;
            while ((c = sr.read()) != -1) System.out.print((char)c);
        }

        // 3. 格式化寫入檔案 (含行號)
        try (PrintWriter out = new PrintWriter(
                new BufferedWriter(new FileWriter("output.txt")))) {
            int lineNo = 1;
            try (BufferedReader in = new BufferedReader(new StringReader(data))) {
                String s;
                while ((s = in.readLine()) != null)
                    out.println(lineNo++ + ": " + s);
            }
        }

        // 4. 基本型別儲存與讀取
        try (DataOutputStream dos = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream("data.bin")))) {
            dos.writeDouble(Math.PI);
            dos.writeUTF("π 字串");
        }
        try (DataInputStream dis = new DataInputStream(
                new BufferedInputStream(new FileInputStream("data.bin")))) {
            System.out.println("\nDouble: " + dis.readDouble());
            System.out.println("UTF: " + dis.readUTF());
        }

        // 5. RandomAccessFile 隨機寫入/讀取
        try (RandomAccessFile raf = new RandomAccessFile("random.dat", "rw")) {
            for (int i = 0; i < 10; i++) raf.writeDouble(i * 1.414);
            raf.seek(5 * 8);               // 跳到第 6 個 double
            raf.writeDouble(47.0001);      // 覆寫
            raf.seek(0);
            for (int i = 0; i < 10; i++) System.out.println("Value " + i + ": " + raf.readDouble());
        }
    }
}

七、關鍵最佳實務

  1. 一律使用 try-with-resources (JDK 7+) 自動關閉資源,避免洩漏。
  2. 指定編碼:new InputStreamReader(is, "UTF-8"),避免平台預設編碼差異。
  3. 大檔案必用緩衝:BufferedInputStream/Reader 減少系統呼叫次數。
  4. 二進位資料用 DataInput/OutputStream,保證跨平台位元序一致性。
  5. 文字處理優先用字元流,自動處理編碼轉換與行尾符。

結語

Java IO 採用裝飾模式組合靈活功能,理解「節點流決定來源/去向,裝飾流增加能力」的設計哲學,配合 try-with-resources 與明確編碼指定,即能寫出健壯、高效、跨平台的 IO 程式碼。

copyright © 萬盛學電腦網 all rights reserved