如何删除android中的内部存储文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3554722/
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
How to delete internal storage file in android?
提问by maxsap
I have used the Android internal storage to save a file for my application (using openFileOutput
) but I would like to delete that file, is it possible and how?
我已使用 Android 内部存储为我的应用程序保存文件(使用openFileOutput
),但我想删除该文件,是否可能以及如何删除?
回答by plugmind
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
回答by Barry
回答by Kailas Bhakade
If you want to delete all files from a folder then use the following function:
如果要删除文件夹中的所有文件,请使用以下功能:
private void deleteTempFolder(String dir) {
File myDir = new File(Environment.getExternalStorageDirectory() + "/"+dir);
if (myDir.isDirectory()) {
String[] children = myDir.list();
for (int i = 0; i < children.length; i++) {
new File(myDir, children[i]).delete();
}
}
}
Folder must be present on storage. If not we can check one more codition for it.
文件夹必须存在于存储中。如果没有,我们可以再检查一个代码。
if (myDir.exists() && myDir.isDirectory()) {
//write same defination for it.
}
回答by Vipul Divyanshu
You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.
您应该始终删除不再需要的文件。删除文件最直接的方法是对打开的文件引用调用 delete() 本身。
myFile.delete()
;
myFile.delete()
;
If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():
如果文件保存在内部存储中,您还可以通过调用 deleteFile() 要求 Context 定位和删除文件:
myContext.deleteFile(fileName);
myContext.deleteFile(fileName);
Note: When the user uninstalls your app, the Android system deletes the following:
All files you saved on internal storage
All files you saved on external storage using getExternalFilesDir()
.
However, you should manually delete all cached files created with getCacheDir()
on a regular basis and also regularly delete other files you no longer need.
注意:当用户卸载您的应用时,Android 系统会删除以下内容: 您保存在内部存储上的所有文件 您使用getExternalFilesDir()
. 但是,您应该手动删除getCacheDir()
定期创建的所有缓存文件,并定期删除您不再需要的其他文件。
Source: http://developer.android.com/training/basics/data-storage/files.html
来源:http: //developer.android.com/training/basics/data-storage/files.html
回答by dev mz
new File(mUri.toString).delete();
回答by djdance
void clearMyFiles() {
File[] files = context.getFilesDir().listFiles();
if(files != null)
for(File file : files) {
file.delete();
}
}
回答by Nijat Ahmadli
Another alternative in Kotlin
Kotlin 的另一种选择
val file: File = context.getFileStreamPath("file_name")
val deleted: Boolean = file.delete()