删除使用 FileOutputStream 创建的文件
我正在为 Android 平台进行开发。
我的应用程序通过简单的调用创建一个临时文件:
FileOutputStream fos = openFileOutput("MY_TEMP.TXT", Mode);
它工作正常,因为我可以正常写入和读取它。
问题是当我退出应用程序时我想删除这个文件。我用过:
File f = new File(System.getProperty("user.dir"), "MY_TEMP.TXT");
f.delete()
但总是返回 false 并且文件没有被删除。
我已经尝试过:
File f = new File("MY_TEMP.TXT");
f.delete();
而且它也不起作用。
I'm developing for the Android platform.
My app creates a temp file with a simple call to:
FileOutputStream fos = openFileOutput("MY_TEMP.TXT", Mode);
It works fine because I can write to it and read it normally.
The problem is that when I exit from the app I want to delete this file. I used:
File f = new File(System.getProperty("user.dir"), "MY_TEMP.TXT");
f.delete()
But it always returns false and the file is not deleted.
I have tried:
File f = new File("MY_TEMP.TXT");
f.delete();
And it does not work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我检查了这篇文章,删除从 FileOutputStream 创建的文件的最佳方法是从 Context 方法 deleteFile(TEMP_FILE) 进行简单调用,就这么简单。
I checked on this posting and the best way to delete a file created from FileOutputStream is a simple call from the Context method deleteFile(TEMP_FILE) as simple as that.
您无法删除已打开的文件。您需要在删除之前关闭流。
也就是说,我宁愿使用
File#createTempFile()
让底层平台进行自动清理工作,避免使用相对路径带来的潜在可移植性问题文件
。You can't delete an opened file. You need to close the stream before delete.
That said, I would rather use
File#createTempFile()
to let the underlying platform do the automatic cleanup work and to avoid potential portability trouble caused by using relative paths inFile
.您需要在删除文件之前关闭该文件。使用下面的代码。
you need to close the file, before deleting it. use below code.
在尝试删除文件之前,请仔细检查流是否已关闭。
Double-check, if the Stream is closed before you attempt to delete the file.
您已经有了一些可靠的答案,但我只想提一下
File.deleteOnExit()
,它会在虚拟机退出时安排删除文件。--edit--
您仍然应该关闭连接到该文件的所有流。
You have some solid answers already, but I just want to mention
File.deleteOnExit()
which schedules a file for deletion when the VM exits.--edit--
You still should close any streams connected to the file.