讀取文本文件是 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();
}
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();
}
finally 關閉邏輯,代碼更簡潔、異常安全。new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8) 顯式聲明字符集,避免平台預設編碼差異導致亂碼。若文件超過記憶體容量,應改用流式處理(逐行業務邏輯)或 Files.lines(Path) (Java 8) 返回 Stream<String> 惰性讀取,配合 try-with-resources 自動關閉流。