【问题标题】:Java save file clears on program restartJava保存文件在程序重新启动时清除
【发布时间】:2023-03-16 11:25:02
【问题描述】:

我试图让我的程序有一个 resume 功能,当用户按下 E 然后重新运行程序时,它会存储以前实例中所有保存的内容程序从该文件中读取以恢复之前的状态(读取/写入ArrayList)。但是,当我尝试写入文件时,文件会保存内容,但重新启动时,文件会被清除。我正在使用 PrintWriter 并附加到我当前的文件以进行保存。

这是我对文件类的写入:

public class fileWrite {

  /* Init writing file PrintWriter objects */
  PrintWriter outFile;
  PrintWriter writeUserInput;

  {
    /* init writer to store all footballclubs current in the league */
    try {
      outFile = new PrintWriter("addcontents.txt");
    } catch(FileNotFoundException e) {
      System.out.println("File failed to be created to save this instance.");
    }
  }

  public fileWrite() {

}

  /* Append a String to the file */
  public void appendString(String s) {
    writeUserInput.append(s + "\n");
    writeUserInput.flush();
  }
  /* Append an Int to the file */
  public void appendInt(int number) {
    writeUserInput.print(number + "\n");
    writeUserInput.flush();
  }
  /* Loop through clubs array and save all information regarding clubs inside file */
  public void storeClubs(ArrayList < FootballClub > footballClubsList) {
    for (FootballClub x: footballClubsList) {
      outFile.println(x.toString());
    }
  }
  /* Close the file writing object */
  public void closeFile() {
    outFile.close();
  }

}

【问题讨论】:

  • 您的文件未关闭或刷新。 closeFile() 是从哪里调用的?
  • 我已经设法修复它。感谢您检查帖子以提供帮助。你是对的,我没有关闭文件。我还使用 FileWriter 为文件设置附加

标签: java file printwriter write


【解决方案1】:

我添加了 FileWriter 并将 appending 设置为 false 以确保不会重写旧内容并附加到末尾(复制数据),仅添加新内容。另外,现在关闭正确的 PrintWriter 对象,以前没有

 /* Loop through clubs array and save all information regarding clubs inside file */
    public void storeClubs(String location, ArrayList<FootballClub> footballClubsList) throws IOException {
        PrintWriter writeContents = new PrintWriter(new FileWriter(location, false));

        for(FootballClub x: footballClubsList)
        {
            writeContents.println(x.toString());
        }
        writeContents.close();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2010-10-17
    • 2015-01-19
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多