删除具有相同名称的文件,仅当新版本可以保存时。

huangapple go评论70阅读模式
英文:

Deleting a file with the same name only if the new version can be saved

问题

我的当前情况是:
我有一个 test.txt 文件,在一段时间间隔后,我想使用相同的名称保存一个更新版本的 test.txt,因为在我的应用程序中,我正在使用 test.txt 名称来读取文件。

我发现使用下面的代码,如果 test.txt 文件已经存在,它基本上会覆盖 test.txt 文件。

new FileWriter("test.txt", false);

我对使用这段代码的主要担忧是,new FileWriter 可能会抛出错误(IOException 和 FileNotFound)。如果无法保存新版本的 test.txt,我不希望它删除旧的 test.txt。

是否有一种方法/选项可以保证只有在能够创建/保存新版本时才删除旧版本的 test.txt?
我不希望陷入旧版本被删除而新版本无法保存的情况。

英文:

My current situation is:
I have test.txt and after an interval i want to save a newer version of test.txt using the same name, because in my application i am using the test.txt name to read the file.

I found that using the code below basically overrides the test.txt file if it already exists.

new FileWriter("test.txt", false);

My main concern using this code is that new FileWriter can throw errors (IOException and FileNotFound). I don't want it to delete the old test.txt if it's not possible to save the new version of test.txt.

Is there a way/option to guarantee that the old version of test.txt gets deleted only if the new version can get created/saved?
I don't want to get stuck in the situation where the old version gets deleted and the new version can't be saved.

答案1

得分: 1

你可以尝试将你的数据写入一个新的临时文件,如果写入完成,就删除test.txt,然后将临时文件重命名为test.txt。

英文:

You could try to write your data to a new temp file and if that is finished delete test.txt and rename the temp file to test.txt.

huangapple
  • 本文由 发表于 2020年9月4日 01:32:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63728883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定