I'm creating temporary file in java but i'm unable to delete it. This is the code I have written:
temp = File.createTempFile("temp", ".txt");
temp.deleteOnExit();
fileoutput = new FileWriter(temp);
buffout = new BufferedWriter(fileoutput);
解决方案
Add the following code (after you have done your operations with the file):
buffout.close();
fileoutput.close();
temp.delete();
As long as some stream on the file is open, it is locked (at least on the windows-implementation of the JVM). So it cannot be deleted.
It is good practice always to check if all opened streams get closed again after usage, because this is a bad memory-leak-situation. Your application can even eat up all available file-handles, that can lead to an unusable system.
本文探讨了Java中创建临时文件时遇到无法删除的问题,指出原因是文件流未关闭导致锁定。解决办法是在操作完成后确保所有流关闭,避免内存泄漏和系统资源耗尽。作者强调了检查并关闭流的重要性,以防止文件句柄耗尽和系统稳定性下降。
943

被折叠的 条评论
为什么被折叠?



