简体   繁体   中英

Deleting files created with FileOutputStream

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.

我检查了这个帖子,删除从FileOutputStream创建的文件的最好方法是从Context方法deleteFile(TEMP_FILE)中简单调用就这么简单。

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 .

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();

如果在您尝试删除文件之前关闭Stream,请仔细检查。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM