我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。

这可能吗?如果可能,怎么可能?


当前回答

这种方法适用于只包含文件的文件夹,但如果您正在寻找还包含子文件夹的场景,则需要递归

此外,您应该捕获返回的返回值,以确保允许您删除该文件

,包括

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

其他回答

如果你不需要递归删除东西,你可以尝试这样做:

File file = new File(context.getExternalFilesDir(null), "");
    if (file != null && file.isDirectory()) {
        File[] files = file.listFiles();
        if(files != null) {
            for(File f : files) {   
                f.delete();
            }
        }
    }

根据文档:

如果此抽象路径名不表示目录,则此方法返回null。

所以你应该检查listFiles是否为空,如果不是则继续

boolean deleteDirectory(File path) {
    if(path.exists()) {
        File[] files = path.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteDirectory(file);
            } else {
                boolean wasSuccessful = file.delete();
                if (wasSuccessful) {
                    Log.i("Deleted ", "successfully");
                }
            }
        }
    }
    return(path.delete());
}

这是kotlin选项。它运行得很好。

fun executeDelete(context: Context, paths: List<String>): Int {
    return try {
        val files = paths.map { File(it) }
        val fileCommands = files.joinToString(separator = " ") {
            if (it.isDirectory) "'${it.absolutePath}/'" else "'${it.absolutePath}'"
        }
        val command = "rm -rf $fileCommands"
        val process = Runtime.getRuntime().exec(arrayOf("sh", "-c", command))
        val result = process.waitFor()
        if (result == 0) {
            context.rescanPaths(paths)
        }
        result
    } catch (e: Exception) {
        -1
    }
}

//避免在一行中多次调用,它可以删除整个文件夹内容

fun Context.rescanPaths(paths: List<String>, callback: (() -> Unit)? = null) {
if (paths.isEmpty()) {
    callback?.invoke()
    return
}

var cnt = paths.size
MediaScannerConnection.scanFile(applicationContext, paths.toTypedArray(), null) { _, _ ->
    if (--cnt == 0) {
        callback?.invoke()
    }
}
}

这就是我的工作…(简洁且经过测试)

    ...
    deleteDir(new File(dir_to_be_deleted));
    ...

    // delete directory and contents
    void deleteDir(File file) { 
        if (file.isDirectory())
            for (String child : file.list())
                deleteDir(new File(file, child));
        file.delete();  // delete child file or empty directory
    }

使用以下方法删除包含文件的整个主目录及其子目录。再次调用此方法后,调用主目录的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();
}