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

Java运行main方法后food.data空文件内容自动清空问题如何解决?

解答

问题原因

PrintWriter单字符串参数的构造方法new PrintWriter("文件路径")默认以覆盖模式打开文件,执行这行代码的瞬间就会清空目标文件的原有内容,和后续是否写入内容、是否关闭流无关。你代码中的Scanner读取操作不会修改文件,问题完全来自PrintWriter的实例化逻辑。

解决方案

根据你的实际需求选择对应方案:

  • 若不需要对food.data执行写入操作,直接删除PrintWriter pw = new PrintWriter("food.data");这行代码即可,仅保留读取逻辑不会修改原文件。
  • 若需要在原有内容基础上追加写入,改用追加模式的流构造PrintWriter:
// FileWriter第二个参数设为true代表开启追加模式,不会清空原有内容
PrintWriter pw = new PrintWriter(new FileWriter("food.data", true));

补充提示:IO流使用完成后需主动调用close()释放资源,也可以使用Java 7+提供的try-with-resources语法自动管理流的关闭,避免资源泄漏:

public static void main(String[] args) throws IOException {
    try (Scanner inFile = new Scanner(new FileReader("food.data"));
         PrintWriter pw = new PrintWriter(new FileWriter("food.data", true))) {
        // 读写逻辑写在这里
    }
}

内容的提问来源于stack exchange,提问作者Shma NB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:42:01