Java – delete the final file during catch vs. delete the temporary file during output file

This is in Java 6

I've seen people create temporary files, do something, and then rename them to output files more than once Everything is contained in a try finally block. Finally, there will be problems in the case of temporarily deleting temporary files

try {
    //do something with tempFile
    //do something with tempFile
    //do something with tempFile
    tempFile.renameTo(outputFile);
}
finally {
    if (tempFile.exists())
        tempFile.delete()
}

I want to know the benefits of this, instead of doing something directly to the output file and deleting it if an exception occurs

try {
    //do something with outputFile
    //do something with outputFile
    //do something with outputFile
}
catch (Exception e) {
    if (outputFile.exists())
        outputFile.delete();
}

My guess is that when the try block can throw a variety of exceptions, deleting temporary files will eventually benefit me Am I right? What else?

Solution

Finally, it is always executed, while the above catch is not executed from Java Lang. error derived exception, and it will also delete the file when it cannot be renamed (this operation will not throw an exception when it fails... An ancient error in Java io

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>