【发布时间】: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