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

Java写入文件后文件为空的问题排查及解决方法咨询

修复FileWriter写入后文件为空的问题

你的代码里,FileWriter默认依赖内存缓冲区暂存写入内容,只有刷新缓冲区或关闭流时,内容才会真正写入磁盘文件,这就是battle.txt为空的原因。下面是几种可行的修复方案:

方案1:每次写入后主动刷新缓冲区

修改print方法,在调用write后立即执行flush(),强制把缓冲区内容写入文件:

protected void print(String me){
    try {
        f.write(me);
        f.flush(); // 刷新缓冲区,写入磁盘
        System.out.println(me);
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

方案2:程序结束时关闭文件流

关闭FileWriter时会自动刷新缓冲区,你可以给Arena类添加关闭方法,在程序退出前调用:

public class Arena  {
    FileWriter f = createFile();

    protected void print(String me){
        try {
            f.write(me);
            System.out.println(me);
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

    protected FileWriter createFile() {
        try {
            return new FileWriter("src/battle.txt");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            System.exit(1);
            return null;
        }
    }

    // 新增关闭方法
    public void closeFile() {
        try {
            if (f != null) {
                f.close();
            }
        } catch (IOException e) {
            System.out.println("Error closing file.");
            e.printStackTrace();
        }
    }
}

使用时记得调用closeFile():

public static void main(String[] args) {
    Arena arena = new Arena();
    arena.print("Test content");
    arena.closeFile(); // 必须调用,确保内容写入
}

方案3:用try-with-resources自动管理流(推荐)

Java 7及以上支持的try-with-resources语法,会在代码块结束时自动关闭流,无需手动调用flush或close,还能避免异常导致的资源泄漏:

public class Arena  {
    protected void print(String me){
        // try-with-resources会自动关闭FileWriter
        try (FileWriter f = new FileWriter("src/battle.txt", true)) {
            // 第二个参数true表示追加写入,默认false会覆盖文件
            f.write(me);
            System.out.println(me);
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

额外注意

  • 相对路径src/battle.txt需要确保程序运行时的工作目录下存在src文件夹,否则会抛出文件找不到异常。
  • 如果程序异常崩溃,方案1和2可能来不及执行flush/close导致内容丢失,方案3是最安全的选择。

内容的提问来源于stack exchange,提问作者Anchr anchr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:20:48