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

Java 文件操作實戰:寫入、讀取與清空 TXT 文件完整代碼範例

     編輯:Java 相關知識

前言

在 Java 開發中,將資料持久化到本地文件是常見需求。本文提供完整、可直接運行的代碼範例,涵蓋 寫入內容到 TXT 文件、讀取文件內容 以及 清空文件內容 三大核心操作,並採用 try-with-resources 自動關閉資源,避免資源洩漏。

1. 將內容寫入 TXT 文件(支援追加模式)

以下方法會自動創建目錄與文件,並以 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 確保流正確關閉。

2. 讀取文件內容(逐行讀取)

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 提供高效的逐行讀取。
  • 編碼一致性:讀取時編碼(GBK)必須與寫入時一致。
  • 異常處理:統一捕獲異常並記錄日誌,避免程式中斷。

3. 清空文件內容(保留文件本身)

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)提升性能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved