定期使用 PrintWriter,数据来自数据库。
在当前运行中完全完成 xml 的生成之前,我不想删除现有的 xml 文件,因为如果在生成 xml 时出现任何问题,我将没有 xml 文件。
将不胜感激有关处理此场景的任何建议,其中当前文件的删除将推迟,直到在当前运行中生成/写入文件完全完成。
On a regular interval am writing to an xml file at a specified location using PrintWriter with data coming from database.
I don't want to delete the existing xml file until the generation of xml is fully completed in current run as in case of any issues while generating xml i would be left with no xml file.
Would appreciate any recommendations around handling this scenario wherein the deletion of current file will hold off until generating/writing the file in the current run is fully completed.
发布评论
评论(2)
您可以将新的 XML 写入临时文件,然后移动/重命名旧文件,然后将临时文件移动/重命名为真实文件名,最后删除旧文件。这样,您始终有一个文件就位,并且在新文件就位之前不会删除旧文件。
You could write the new XML to a temp file, then move/rename the old file, then move/rename the temp file to the real file name, and finally delete the old file. That way you always have a file in place and don't delete the old file until the new file is in place.
执行此类操作的最常见方法是使用不同的文件名重命名原始 XML 文件。
简单版本:
此版本的缺陷是,如果应用程序(或系统)在重命名后失败,则下次运行该应用程序时可能会看到不完整或丢失的
'file.xml'
。您可以通过让应用程序在检测到任一情况时尝试使用备份文件来解决此问题。或者,您可以引入第三个文件;例如,让应用程序生成
'file.xml.new'
并在写入成功后进行重命名。在某些情况下,您仍然必须处理丢失的'file.xml'
:除非您有事务性文件系统,否则这是不可避免的。但是,失败的窗口较小,您应该始终完成当前文件和备份文件的副本。The most common way to do this kind of thing is to rename the original XML file with a different filename.
Simple version:
The flaw in this version is that if the application (or system) fails after renaming, the next time you run that application may see an incomplete or missing
'file.xml'
. You can address this by having the application try to use the backup file if it detects either scenario.Alternatively, you can introduce a third file; e.g. get the application to generate
'file.xml.new'
and do the renaming AFTER the write has succeeded. You still have to cope with a missing'file.xml'
under some circumstances: it is unavoidable unless you have a transactional file system. However, the window for failure is smaller, and you should always complete copies of the current and backup files.