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

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


当前回答

我用这个递归函数来做这个工作:

public static void deleteDirAndContents(@NonNull File mFile){
    if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
        for (File file : mFile.listFiles()) {
            deleteDirAndContents(file);
        }
    } else {
        mFile.delete();
    }
}

该函数检查它是目录还是文件。

如果是目录检查它是否有子文件,如果有子文件将再次调用自己传递子文件并重复。

如果它是一个文件,它删除它。

(不要使用这个函数通过传递缓存目录来清除应用程序缓存,因为它也会删除缓存目录,所以应用程序会崩溃… 如果你想清除缓存,你可以使用这个函数,它不会删除你传递给它的dir:

public static void deleteDirContents(@NonNull File mFile){
        if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
            for (File file : mFile.listFiles()) {
                deleteDirAndContents(file);
            }
        }
    }

或者你可以检查它是否是缓存目录使用:

if (!mFile.getAbsolutePath().equals(context.getCacheDir().getAbsolutePath())) {
    mFile.delete();
}

清除应用程序缓存的示例代码:

public static void clearAppCache(Context context){
        try {
            File cache = context.getCacheDir();
            FilesUtils.deleteDirContents(cache);
        } catch (Exception e){
            MyLogger.onException(TAG, e);
        }
    }

再见,有一个美好的一天&编码:D

其他回答

如果该目录在Java中有子目录或文件,则不能删除该目录。试试这两行简单的解决方案。这将删除目录和目录内的竞争。

File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);

在gradle文件中添加这一行并同步项目

compile 'org.apache.commons:commons-io:1.3.2'  

这里是一个非递归的实现,只是为了好玩:

/**
 * Deletes the given folder and all its files / subfolders.
 * Is not implemented in a recursive way. The "Recursively" in the name stems from the filesystem command
 * @param root The folder to delete recursively
 */
public static void deleteRecursively(final File root) {
    LinkedList<File> deletionQueue = new LinkedList<>();
    deletionQueue.add(root);

    while(!deletionQueue.isEmpty()) {
        final File toDelete = deletionQueue.removeFirst();
        final File[] children = toDelete.listFiles();
        if(children == null || children.length == 0) {
            // This is either a file or an empty directory -> deletion possible
            toDelete.delete();
        } else {
            // Add the children before the folder because they have to be deleted first
            deletionQueue.addAll(Arrays.asList(children));
            // Add the folder again because we can't delete it yet.
            deletionQueue.addLast(toDelete);
        }
    }
}

最快最简单的方法:

public static boolean deleteFolder(File removableFolder) {
        File[] files = removableFolder.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                boolean success;
                if (file.isDirectory())
                    success = deleteFolder(file);
                else success = file.delete();
                if (!success) return false;
            }
        }
        return removableFolder.delete();
}

这(尝试删除所有子文件和子目录,包括提供的目录):

如果是文件,删除 如果是空目录,请删除 如果不是空目录,再次调用删除子目录,重复1到3

例子:

File externalDir = Environment.getExternalStorageDirectory()
Utils.deleteAll(externalDir); //BE CAREFUL.. Will try and delete ALL external storage files and directories

访问“外部存储目录”需要具备以下权限:

(使用ContextCompat。checkSelfPermission和ActivityCompat.requestPermissions)

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

递归方法:

public static boolean deleteAll(File file) {
    if (file == null || !file.exists()) return false;

    boolean success = true;
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isDirectory()) {
                    success &= deleteAll(f);
                }
                if (!f.delete()) {
                    Log.w("deleteAll", "Failed to delete " + f);
                    success = false;
                }
            }
        } else {
            if (!file.delete()) {
                Log.w("deleteAll", "Failed to delete " + file);
                success = false;
            }
        }
    } else {
        if (!file.delete()) {
            Log.w("deleteAll", "Failed to delete " + file);
            success = false;
        }
    }
    return success;
}

让我告诉你第一件事你不能删除DCIM文件夹,因为它是一个系统文件夹。当你在手机上手动删除它时,它会删除该文件夹的内容,但不会删除DCIM文件夹。您可以通过以下方法删除其内容:

根据评论更新

File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {
       new File(dir, children[i]).delete();
    }
}