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;
}
new InputStreamReader(inputStream, charset) 是跨平台讀取中文檔案的關鍵,避免預設編碼導致亂碼。FileInputStream(位元組)→ InputStreamReader(位元組→字元,指定編碼)→ BufferedReader(緩衝讀行)。finally 區塊關閉 reader,close() 會連帶關閉底層串流。content += line 簡單明瞭,但大檔案會產生大量暫時字串。實務上大檔案請用 StringBuilder 或逐行處理,避免記憶體暴漲。
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,即能寫出正確、高效、可維護的檔案讀取程式碼。