You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java BufferedWriter写文件异常:仅写入最后一条记录

Fix: Only Last Record Writes to File in Your LerEscreverArquivo Class

Hey there! This is a super common gotcha with Java file I/O—let’s break down why only your last record is making it to the file, and how to fix it fast.

The Root Cause

Chances are, you’re creating a new file writer inside your loop (for every single record) and using the default file mode, which overwrites the entire file every time you open it. So each new record replaces the previous one, leaving only the final entry when the loop finishes.

Example of the Problematic Pattern

Here’s what your buggy code might look like (even if the syntax isn’t exact, this is the core issue):

// ❌ Bad: Creates a new writer for each record, overwriting the file every time
for (String processedRecord : yourProcessedDataList) {
    FileWriter writer = new FileWriter("output.txt");
    writer.write(processedRecord);
    writer.close();
}

The Simple Fix

You need to create your file writer once, outside the loop, and choose one of these two approaches based on your needs:

Option 1: Append to an Existing File

If you want to add new records to a file that already has content, use the FileWriter constructor with a second boolean parameter (true enables append mode):

// ✅ Good: Creates one writer, appends all records to the file
try (FileWriter writer = new FileWriter("output.txt", true)) {
    for (String processedRecord : yourProcessedDataList) {
        writer.write(processedRecord + System.lineSeparator()); // Add newline for readability
    }
} catch (IOException e) {
    e.printStackTrace();
    // Add proper error handling here (log it, notify the user, etc.)
}

Option 2: Overwrite the File with All Records

If you want to replace the entire file with your processed data (instead of appending), omit the true parameter but still keep the writer outside the loop:

// ✅ Good: Overwrites the file once, writes all records in one go
try (FileWriter writer = new FileWriter("output.txt")) {
    for (String processedRecord : yourProcessedDataList) {
        writer.write(processedRecord + System.lineSeparator());
    }
} catch (IOException e) {
    e.printStackTrace();
}

Key Tips

  • We’re using try-with-resources syntax here (try (FileWriter writer = ...)), which automatically closes the writer when done—no need to call writer.close() manually, and it prevents resource leaks.
  • System.lineSeparator() ensures your records are on separate lines across all operating systems (Windows uses \r\n, Unix-like systems use \n).

If you’re using a different writer class (like BufferedWriter), the same logic applies: create the writer once outside the loop, and use append mode if needed.

内容的提问来源于stack exchange,提问作者Kakashi - Sensei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:25:12