在java中删除临时文件 [英] delete temporary file in java

查看:300
本文介绍了在java中删除临时文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中创建临时文件,但我无法删除它。这是我写的代码:

  temp = File.createTempFile(temp,.txt); 
temp.deleteOnExit();
fileoutput = new FileWriter(temp);
buffout = new BufferedWriter(fileoutput);


解决方案

添加下面的代码与文件):

  buffout.close(); 
fileoutput.close();
temp.delete();

只要文件上的某个数据流打开,它就会被锁定(至少在windows- JVM的实现)。所以它不能被删除。



最好的做法是检查所有打开的流在使用后是否再次关闭,因为这是一个糟糕的内存泄漏情况。您的应用程序甚至会吃掉所有可用的文件句柄,这可能导致系统不可用。


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中删除临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆