GB 級文本文件按行讀取,BufferedReader.readLine() 經典可靠;RandomAccessFile 支持隨機訪問;NIO FileChannel + ByteBuffer 適合高併發大吞吐。本文提供三套完整代碼與選型指南。
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
process(line);
}
}
InputStreamReader 指定 charset)try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
// 順序讀行
String line;
while ((line = raf.readLine()) != null) { process(line); }
// 隨機跳轉:seek(position) 後 readLine()
raf.seek(1024 * 1024); // 跳到 1MB 處
}
seek() 定位字節偏移,適合斷點續傳、分片處理readLine() 實現簡陋(不識別 \r\n),建議自行實現行讀取邏輯try (FileChannel in = FileChannel.open(path, StandardOpenOption.READ);
FileChannel out = FileChannel.open(outPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 1024); // 1MB 直接內存
while (in.read(buf) != -1) {
buf.flip();
out.write(buf);
buf.clear();
}
}
allocateDirect 分配堆外內存,避免 JVM 堆壓力,零拷貝(OS 層面)transferTo/transferFrom 可進一步利用 DMA 零拷貝涵蓋四種讀取模式:
readFileByBytes():字節流(圖片/視頻/二進制)readFileByChars():字符流(文本),處理 \r\n 換行兼容readFileByLines():按行讀取(日志/CSV/配置)readFileByRandomAccess():隨機訪問(大文件分片)// A: RandomAccessFile seek 到末尾
raf.seek(raf.length());
raf.writeBytes(content);
// B: FileWriter append 模式
new FileWriter(file, true).write(content);
| 場景 | 推薦方案 | 核心理由 |
|---|---|---|
| 順序讀文本、逐行處理 | BufferedReader | API 簡單、編碼安全、換行自適應 |
| 大文件隨機讀取、斷點續讀 | RandomAccessFile | seek() 精確定位字節偏移 |
| 大文件複製、高併發讀寫、零拷貝 | NIO FileChannel + DirectBuffer | 堆外內存、OS 零拷貝、可擴展 |
| 二進制文件(圖片/視頻) | FileInputStream + BufferedInputStream | 字節流語義正確 |