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

Java 範例:指定編碼讀取文字檔案內容

     編輯:Java 相關知識

InputStreamReader 建構子提供 charset 參數,可指定將位元組串流轉為字元時的編碼(如 UTF-8、Big5、MS950)。以下封裝為可重用方法,示範正確資源管理與編碼指定。

完整程式碼


/**
 * 讀取指定文字檔案並回傳內容
 * @param path 檔案路徑
 * @param charset 檔案編碼(如 "UTF-8", "Big5")
 * @return 檔案完整內容
 * @throws IOException 檔案不存在、開啟失敗或讀取失敗
 */
private static String readFile(String path, String charset) throws IOException {
    String content = "";
    BufferedReader reader = null;
    try {
        // FileInputStream → InputStreamReader(指定編碼) → BufferedReader
        reader = new BufferedReader(
            new InputStreamReader(new FileInputStream(path), charset)
        );
        String line;
        while ((line = reader.readLine()) != null) {
            content += line + "\n";
        }
    } finally {
        // 確保關閉 Reader,避免資源洩漏
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // 關閉時例外通常可忽略
            }
        }
    }
    return content;
}

關鍵點解析

  1. 編碼指定:new InputStreamReader(inputStream, charset) 是跨平台讀取中文檔案的關鍵,避免預設編碼導致亂碼。
  2. 串流包裝順序:FileInputStream(位元組)→ InputStreamReader(位元組→字元,指定編碼)→ BufferedReader(緩衝讀行)。
  3. 資源釋放:finally 區塊關閉 reader,close() 會連帶關閉底層串流。
  4. 字串拼接效能:範例用 content += line 簡單明瞭,但大檔案會產生大量暫時字串。實務上大檔案請用 StringBuilder 或逐行處理,避免記憶體暴漲。

進階補充:Java 7+ try-with-resources 更簡潔


private static String readFile(String path, String charset) throws IOException {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(new FileInputStream(path), charset))) {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    }
    return sb.toString();
}
  • 自動關閉資源,無需 finally。
  • 使用 StringBuilder 避免字串拼接效能問題。

小結

指定編碼讀取檔案,核心在於 InputStreamReader 的第二個參數。掌握串流包裝鏈與資源管理模式,配合 try-with-resources 與 StringBuilder,即能寫出正確、高效、可維護的檔案讀取程式碼。

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