java web临时文件删除,在java中删除临时文件

本文探讨了Java中创建临时文件时遇到无法删除的问题,指出原因是文件流未关闭导致锁定。解决办法是在操作完成后确保所有流关闭,避免内存泄漏和系统资源耗尽。作者强调了检查并关闭流的重要性,以防止文件句柄耗尽和系统稳定性下降。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值