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

Java 讀取文本文件最佳實踐:BufferedReader 完整範例

     編輯:Java 相關知識

標準讀取範例

使用 BufferedReader 包裝 FileReader,逐行讀取並保留換行符,配合 try-with-resources 或 finally 確保資源釋放。

完整代碼

import java.io.*;

public class ReadTextFileExample {
    public static void main(String[] args) {
        File file = new File("test.txt");
        StringBuilder contents = new StringBuilder();
        
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contents.append(line)
                        .append(System.lineSeparator());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        System.out.println(contents.toString());
    }
}

關鍵點解析

要點說明
BufferedReader提供緩衝讀取,大幅提升 I/O 性能
readLine()不包含換行符,需手動添加 System.lineSeparator()
StringBuilder非線程安全但高效,單線程場景優於 StringBuffer
try-with-resourcesJava 7+ 自動關閉實現 AutoCloseable 的資源
異常處理分別捕獲 FileNotFoundException 與 IOException

現代替代方案(Java 7+)

Files.readAllLines(小文件)

List lines = Files.readAllLines(Paths.get("test.txt"), StandardCharsets.UTF_8);
String content = String.join(System.lineSeparator(), lines);

Files.lines(大文件流式處理)

try (Stream stream = Files.lines(Paths.get("test.txt"))) {
    stream.forEach(System.out::println);
}

編碼指定最佳實踐

// 顯式指定編碼,避免平台預設編碼差異
new FileReader(file)  // 依賴平台預設編碼,不推薦
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)  // 推薦

選擇適合場景的讀取方式,兼顧性能與代碼簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved