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

Java程序重启后文件内容丢失,如何恢复ArrayList数据?

问题分析

你的程序每次重启后文件内容被清空,核心原因有两个:

  1. 程序启动时没有读取已存在的文件内容到ArrayList,导致memory每次启动都是空集合,写入文件时直接覆盖了原有内容。
  2. FileWriter默认使用覆盖模式写入文件,即使你想追加,由于memory中没有历史数据,最终还是会丢失之前的笔记。
解决方案

要实现"保存所有内容+重启加载"的需求,需要补全启动加载文件的逻辑,并确保写入时包含所有历史笔记。

1. 添加笔记加载方法

在程序启动时,读取notes.data中的所有内容并加载到memory中:

public void loadNotes() {
    try (BufferedReader reader = new BufferedReader(new FileReader("notes.data"))) {
        String line;
        while ((line = reader.readLine()) != null) {
            memory.add(line);
        }
    } catch (FileNotFoundException e) {
        // 首次运行文件不存在,无需处理
    } catch (IOException e) {
        System.out.println("加载笔记失败: " + e.getMessage());
    }
}

在类的构造方法或程序入口处调用这个方法,比如:

// 假设你的类名为NoteManager
public NoteManager() {
    memory = new ArrayList<>();
    loadNotes(); // 启动时加载已有笔记
}

2. 优化文件写入逻辑

保留覆盖式写入(因为memory已经包含所有笔记),但改用try-with-resources自动关闭流,避免资源泄漏:

public void fileHandling() {
    try (FileWriter fWriter = new FileWriter("notes.data")) {
        for (String note : memory) {
            fWriter.write(note + '\n');
        }
    } catch (IOException e) {
        System.out.println("保存笔记失败: " + e.getMessage());
    }
}

3. 修复输入判断逻辑

Scanner.nextLine()不会返回null,你的空输入判断无效,改成检查空字符串:

public void createNote() {
    Scanner insertNote = new Scanner(System.in);
    LocalDate todayDate = LocalDate.now();
    LocalTime nowTime = LocalTime.now();
    String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
    String dateTime = todayDate.toString() + " at " + timeFormat;

    while (true) {
        System.out.println();
        System.out.println("Enter a note");
        System.out.print("> ");
        String note = insertNote.nextLine();

        if (note.trim().isEmpty()) {
            System.out.println("Invalid input! Try again");
            break;
        } else {
            memory.add(note + " /" + dateTime);
            fileHandling();
            System.out.println("Note is saved!\n");
            break;
        }
    }
}
工作流程说明
  1. 程序启动时,loadNotes()读取notes.data的所有行,存入memory。
  2. 用户添加新笔记时,新内容被追加到memory。
  3. 调用fileHandling()将memory中的所有内容(历史+新笔记)写入文件,覆盖原有内容,保证文件内容与内存完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:30:53