AnonymousUser12
AnonymousUser12

Reputation: 1

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

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.

Upvotes: 0

Views: 249

Answers (1)

flimosch
flimosch

Reputation: 36

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.

Upvotes: 1

Related Questions