Java 删除使用 FileOutputStream 创建的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3291255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting files created with FileOutputStream
提问by
I'm developing for the Android platform.
My app creates a temp file with a simple call to:
我正在为 Android 平台开发。
我的应用程序通过简单的调用创建了一个临时文件:
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:
但它总是返回 false 并且文件不会被删除。
我试过了:
File f = new File("MY_TEMP.TXT");
f.delete();
And it does not work either.
它也不起作用。
采纳答案by Palomo
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.
我查看了这篇文章,删除从 FileOutputStream 创建的文件的最佳方法是从 Context 方法 deleteFile(TEMP_FILE) 的简单调用,就这么简单。
回答by BalusC
You can't delete an opened file. You need to close the stream before delete.
您无法删除打开的文件。您需要在删除之前关闭流。
fos.close();
f.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 in File
.
也就是说,我宁愿File#createTempFile()
让底层平台做自动清理工作,并避免在File
.
回答by Andreas Dolk
Double-check, if the Stream is closed before you attempt to delete the file.
在尝试删除文件之前,请仔细检查 Stream 是否已关闭。
回答by willcodejavaforfood
You have some solid answers already, but I just want to mention File.deleteOnExit()
which schedules a file for deletion when the VM exits.
您已经有了一些可靠的答案,但我只想提一下File.deleteOnExit()
,哪个计划在 VM 退出时删除文件。
--edit--
- 编辑 -
You still should close any streams connected to the file.
您仍然应该关闭连接到文件的任何流。
回答by Palomo
you need to close the file, before deleting it. use below code.
您需要先关闭该文件,然后再删除它。使用下面的代码。
FileOutputStream fos = openFileOutput("MY_TEMP.TXT",Mode);
File f = new File(System.getProperty("user.dir"),"MY_TEMP.TXT");
fos.close();
File f = new File("MY_TEMP.TXT");
f.delete();