gpt4 book ai didi

java - PrintWriter:读取和写入同一文件 - 文件在再次打开之前似乎未保存

转载 作者:搜寻专家 更新时间:2023-11-01 03:09:13 25 4
gpt4 key购买 nike

我正在尝试创建一个将新数据写入保存文件的程序。该文件具有三个“插槽”,即三个由分隔符分隔的字符串。主程序以slot为参数调用saver程序,saver程序打开文件,将每个slot中已有的String读入局部变量,用新的String替换给定slot对应的,并覆盖文件与新插槽。这应该会导致仅更新给定的插槽,而其他两个与以前相同。

主程序连续三次调用saver,每个slot一次。这应该导致保存文件如下所示(其中 # 是分隔符):

在第一次调用之前:#EMPTY#EMPTY#EMPTY

第一次调用后:#NewString#EMPTY#EMPTY

第二次调用后:#NewString#NewString#EMPTY

第三次调用后:#NewString#NewString#NewString

.

取而代之的是:

在第一次调用之前:#EMPTY#EMPTY#EMPTY

第一次调用后:#NewString#EMPTY#EMPTY

第二次调用后:#EMPTY#NewString#EMPTY

第三次调用后:#EMPTY#EMPTY#NewString

printwriter (PrintWriter saver = new PrintWriter(new FileWriter(fileName))) 在保护文件中打开,而不是在主文件中打开,因此每次调用都会打开一个新的 PrintWriter。我 .flush() 和 .close() 在 saver 方法的末尾(这是一个 void 方法)。

为什么在下一次调用该方法之前文件似乎没有保存? =S 我是否必须强制执行某种 wait-until-file-isn't-open-anymore 命令,如果是这样,我该怎么做?

public static void main(String[] args) throws IOException {

SaveGame.saveState("adventure/save/s1.save", new Adventure(), 0);

SaveGame.saveState("adventure/save/s2.save", new Adventure(), 1);

SaveGame.saveState("adventure/save/s3.save", new Adventure(), 2);
}

然后:

public class SaveGame {

public static void saveState(String fileName, Adventure a, int slot) throws IOException {

//UPDATE MASTER SAVE FILE save.txt
String[] save = new String[3];

try {
Scanner openSave = new Scanner(new FileReader("/adventure/save/save.txt"));
openSave.useDelimiter("#");
save[0] = openSave.next();
save[1] = openSave.next();
save[2] = openSave.next();
openSave.close();
}
catch (FileNotFoundException e) {
save[0] = "EMPTY";
save[1] = "EMPTY";
save[2] = "EMPTY";
}

save[slot] = "newString"; //change the CURRENT save in the given slot to the new

PrintWriter updater = new PrintWriter(new FileWriter("adventure/save/save.txt"));
updater.println("#" + save[0] + "#" + save[1] + "#" + save[2]);
updater.flush();
updater.close();

最佳答案

读者读取文件/adventure/save/save.txt,而作者写入adventure/save/save.txt。除非您从文件系统的根目录 (/) 运行该程序,否则这些文件不是相同的文件。

应用 DRY 原则(不要重复自己)。创建一个包含文件路径的常量,并在您使用该路径的任何地方使用该常量。这将避免此类错误。

此外,在 finally block 中关闭读取器和写入器,或使用 Java 7 try-with-resources 结构。

关于java - PrintWriter:读取和写入同一文件 - 文件在再次打开之前似乎未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com