在 Java 開發中,將資料持久化到本地文件是常見需求。本文提供完整、可直接運行的代碼範例,涵蓋 寫入內容到 TXT 文件、讀取文件內容 以及 清空文件內容 三大核心操作,並採用 try-with-resources 自動關閉資源,避免資源洩漏。
以下方法會自動創建目錄與文件,並以 GBK 編碼追加寫入內容:
public static void writeFile() {
String txtFileName = "emailRecord.txt";
String directoryPath = "";
try {
// 獲取 Web 應用的真實路徑(根據實際框架調整)
directoryPath = WebplusContext.getRealPath("/apps/schoolfellow/upload/smsRecord");
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs(); // 遞歸創建目錄
}
File txtFile = new File(directoryPath, txtFileName);
// true 表示追加模式;使用 try-with-resources 自動關閉流
try (FileOutputStream out = new FileOutputStream(txtFile, true)) {
String line = System.lineSeparator(); // 跨平台換行符
String smsContent = "將內容寫入 txt 文件!" + line;
out.write(smsContent.getBytes("GBK")); // 指定編碼
}
} catch (Exception ex) {
log.error("寫入文件失敗!", ex);
}
}
mkdirs() 會創建所有不存在的父目錄。new FileOutputStream(file, true) 第二個參數為 true 時不覆蓋原有內容。getBytes("GBK") 避免中文亂碼;現代項目建議統一使用 StandardCharsets.UTF_8。try-with-resources 確保流正確關閉。public void readerFile() {
String filePath = WebplusContext.getServletContext()
.getRealPath("/apps/schoolfellow/upload/emailRecord/emailRecord.txt");
try (FileInputStream fis = new FileInputStream(filePath);
InputStreamReader reader = new InputStreamReader(fis, "GBK");
BufferedReader br = new BufferedReader(reader)) {
String info;
List<SchoolfellowDataViewWrap> schoolfellows = new ArrayList<>();
while ((info = br.readLine()) != null) {
System.out.println(info);
// 此處可解析 info 並封裝到 schoolfellows 列表
}
} catch (Exception ex) {
log.error("讀取數據失敗", ex);
}
}
BufferedReader 提供高效的逐行讀取。public void clearFileContent() {
String filePath = WebplusContext.getServletContext()
.getRealPath("/apps/schoolfellow/upload/emailRecord/emailRecord.txt");
try (FileOutputStream out = new FileOutputStream(filePath, false)) {
// false 表示不追加,直接截斷文件(長度歸零)
out.write(new byte[0]); // 寫入空位元組陣列即可清空
// 前端提示腳本(根據實際框架調整)
script = "alert('清空發送郵件日誌成功!');";
} catch (Exception ex) {
script = "alert('清空文件內容失敗,可能文件不存在!');";
log.error("清空文件失敗", ex);
}
}
new FileOutputStream(filePath, false) 會以 覆蓋模式 打開文件,自動將文件長度截斷為 0,達到清空效果。無需寫入空字串,直接寫入空位元組陣列 new byte[0] 即可。
try-with-resources 管理 I/O 資源(JDK 7+)。UTF-8 編碼,避免跨平台亂碼。NIO.2 (Files API) 或記憶體映射文件(MappedByteBuffer)提升性能。