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

Java 讀取文本文件內容最佳實踐:BufferedReader 與 try-with-resources

     編輯:Java 相關知識

讀取文本文件是 Java 開發高頻操作。本文對比兩種寫法:傳統 try-catch-finally 手動關流,與現代 try-with-resources 自動資源管理,推薦後者作為標準範式。

基礎版:手動關閉流

public static String readFile(String path) throws IOException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(path));
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append('\n');
        }
    } finally {
        if (reader != null) {
            try { reader.close(); } catch (IOException ignored) {}
        }
    }
    return content.toString();
}

進階版:try-with-resources (Java 7+)

public static String readFile(String path) throws IOException {
    StringBuilder content = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append('\n');
        }
    }
    return content.toString();
}

關鍵優化點

  • StringBuilder 替代 String 拼接:避免循環中產生大量臨時字串對象,顯著提升大文件讀取性能。
  • try-with-resources:編譯器自動生成 finally 關閉邏輯,代碼更簡潔、異常安全。
  • 指定編碼:生產環境建議使用 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8) 顯式聲明字符集,避免平台預設編碼差異導致亂碼。

大文件場景建議

若文件超過記憶體容量,應改用流式處理(逐行業務邏輯)或 Files.lines(Path) (Java 8) 返回 Stream<String> 惰性讀取,配合 try-with-resources 自動關閉流。

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