| 模式 | 適用場景 | 核心類 |
|---|---|---|
| 位元組單讀 | 二進制檔(圖片、音訊) | FileInputStream.read() |
| 位元組批次讀 | 大型二進制檔,效能較好 | FileInputStream.read(byte[]) |
| 字符單讀 | 文字檔,需處理 \\r\\n | InputStreamReader.read() |
| 字符批次讀 | 文字檔,效能較好 | InputStreamReader.read(char[]) |
| 逐行讀取 | 格式化文字(日誌、CSV) | BufferedReader.readLine() |
| 隨機存取 | 大檔案定位讀取、斷點續傳 | RandomAccessFile.seek()/read() |
ReadFromFile 類readFileByBytes():示範單位元組與批次(100 bytes)兩種讀法,含 available() 剩餘位元組數查詢readFileByChars():單字符/批次字符讀取,特別處理 Windows \\r\\n 避免重複換行readFileByLines():逐行讀取並顯示行號,最常用於文字處理readFileByRandomAccess():從第 4 位元組開始讀 10 bytes,展示 seek() 定位RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(raf.length()); // 移至檔尾
raf.writeBytes(content);
raf.close();
FileWriter fw = new FileWriter(file, true); // true = append
fw.write(content);
fw.close();
readFileByLines() 驗證內容完整程式碼已整合於 ReadFromFile 與 AppendToFile 兩個類別中,可直接複製執行觀察結果。