java保存文件在程序重新启动时清除

vfwfrxfs  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(299)

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

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();
  }

}
f45qwnt8

f45qwnt81#

我添加了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();
    }

相关问题