我正在尝试:
-接收文件的内容(称为list.txt),对其进行修改并提交到临时文件(listtemp.txt)中。
-清除list.txt,将listtemp.txt的新内容打印到list.txt中,然后清除listtemp.txt以进一步修改list.txt
问题是,当我在listtemp.txt中具有适当的内容时,我无法获取新内容并将其放入list.txt中。我成功清除了列表,但随后无法使用PrintWriter追加或写入列表。
我尝试使用FileWriter清除list.txt,将参数设置为false以清除它,然后关闭FileWriter,并使用我原来用于打印/附加到list.txt的原始PrintWriter。
我尝试完全删除list.txt,然后重新创建它,然后使用原始的PrintWriter再次打印/附加,直接打印/附加文本文件。
因此,如前所述,我修改了list.txt并将其成功放入listtemp.txt中。然后,我尝试创建一个swapListing()方法来清除list.txt并添加listtemp.txt的内容。
private void swapListing() {
FileWriter fw = null; //This is the temporary FileWriter to clear the text file
try {
fw = new FileWriter(main.file, false); //Main list is cleared.
fw.close();
fw = null;
} catch (IOException e) {
e.printStackTrace();
}
try {
String temp = main.getReader().readFile(main.filetemp); //I got the contents of the String from my listtemp.txt, and I checked, and the String is successfully retrieved, so this isn't the problem.
pwriter.print(temp); // This is where I feel like file SHOULD be appended
} catch(Exception e) {
e.printStackTrace();
}
}
我也尝试删除该文件,但是实际上并没有删除该文件,实际上原始内容也仍然在文件中。
private void clearFile() {
if (main.file.exists()) {
main.file.delete();
try {
main.file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
String temp = main.getReader().readFile(main.filetemp);
pwriter.print(temp);
} catch(Exception e) {
e.printStackTrace();
}
}
我不希望使用delete file方法,但在这一点上,我希望至少可以使用一个可行的解决方案。
答案 0 :(得分:0)
有一个“安全保存”的概念,它甚至还受到操作系统(至少在Windows上)的特殊支持。步骤是:
然后,操作系统将为您应用原始文件的时间戳。在同一磁盘上移动文件是非常快速的操作。必要的修改仅在文件系统结构中。文件内容保留在磁盘上完全相同的位置。
您没有遵循此过程。对我来说,听起来太复杂了
您尚未说明创建pwriter
的方式和时间。它是否使用BufferedWriter
?什么时候关闭?它会完全关闭吗?如果不是,您flush()
吗?如果是这样,什么时候?如果没有,那可能是问题的一部分。