This is in Java 6.
I have seen more than once that people create temporary files, do something, and then rename them to an output file. Everything is wrapped in a try-finally block, where the temporary file is deleted in finallyif something fails between them.
try {
//do something with tempFile
//do something with tempFile
//do something with tempFile
tempFile.renameTo(outputFile);
}
finally {
if (tempFile.exists())
tempFile.delete()
}
I was wondering what advantages can be made, instead of doing something directly with the output file and deleting it in case of exceptions.
try {
//do something with outputFile
//do something with outputFile
//do something with outputFile
}
catch (Exception e) {
if (outputFile.exists())
outputFile.delete();
}
My assumption is that deleting temporary files is finallybeneficial to me when the try block can throw many exceptions. Did I understand correctly? What else?
source
share