我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
当前回答
使用以下方法删除包含文件的整个主目录及其子目录。再次调用此方法后,调用主目录的delete()目录。
// For to Delete the directory inside list of files and inner Directory
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
其他回答
从目录中删除所有文件的简单方法:
它是一个通用函数,用于删除目录中的所有图像
deleteAllImageFile(背景);
public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
if (directory.isDirectory()) {
for (String fileName: file.list()) {
new File(file,fileName).delete();
}
}
}
这种方法适用于只包含文件的文件夹,但如果您正在寻找还包含子文件夹的场景,则需要递归
此外,您应该捕获返回的返回值,以确保允许您删除该文件
,包括
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在你的清单上
void DeleteRecursive(File dir)
{
Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
if (temp.isDirectory())
{
Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
DeleteRecursive(temp);
}
else
{
Log.d("DeleteRecursive", "Delete File" + temp.getPath());
boolean b = temp.delete();
if (b == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
}
}
dir.delete();
}
我知道的最安全的代码:
private boolean recursiveRemove(File file) {
if(file == null || !file.exists()) {
return false;
}
if(file.isDirectory()) {
File[] list = file.listFiles();
if(list != null) {
for(File item : list) {
recursiveRemove(item);
}
}
}
if(file.exists()) {
file.delete();
}
return !file.exists();
}
检查文件是否存在,处理空值,检查目录是否被实际删除
我们可以使用命令行参数删除整个文件夹及其内容。
public static void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) { }
}
}
以上代码的使用示例:
deleteFiles("/sdcard/uploads/");
private static void deleteRecursive(File dir)
{
//Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
deleteRecursive(temp);
}
}
if (dir.delete() == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}