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

如何让FileWriter不覆盖首行,而是将内容追加到新行?

解决FileWriter覆盖首行的问题

问题根源

你遇到的核心问题是FileWriter默认采用覆盖模式打开文件,每次调用new FileWriter("subOrder.txt")时,都会清空文件原有内容再写入——这就是为什么不管你加多少换行符,首行都会被新内容覆盖,换行符只会在空文件里添加空行。

解决方案

直接使用FileWriter的追加模式构造方法,同时在写入内容后添加换行符即可解决:

  1. 修改FileWriter初始化代码,加入第二个参数true,表示以追加模式打开文件:
FileWriter orderTaker = new FileWriter("subOrder.txt", true);
  1. 写入内容时拼接换行符(推荐用System.lineSeparator()适配不同操作系统):
orderTaker.write("6 inch Sub" + System.lineSeparator());

修改后的完整代码片段

if (sub.size.equals("1")) {
    sub.price = sub.price + 7.19;
    try {
        // 启用追加模式,避免覆盖原有内容
        FileWriter orderTaker = new FileWriter("subOrder.txt", true);
        // 写入内容并自动换行
        orderTaker.write("6 inch Sub" + System.lineSeparator());
        orderTaker.close();
    } catch(IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

进阶优化(用BufferedWriter)

如果需要写入大量内容,用BufferedWriter会更高效,写法类似:

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("subOrder.txt", true));
    writer.write("6 inch Sub");
    writer.newLine(); // 专门的跨平台换行方法
    writer.close();
} catch(IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}

内容的提问来源于stack exchange,提问作者Jack Rast

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:30:11