【问题标题】:Delete All file and sub-folder Except the main folder删除除主文件夹外的所有文件和子文件夹
【发布时间】:2023-08-03 09:11:02
【问题描述】:

我是新的安卓应用

在我的应用程序的某些部分,我需要删除 /data/data/PACKAGE_NAME/ 中的所有文件和子文件夹,但保留主文件夹

我也有 root 访问权限!和shell推荐

我使用了两种方法,但都删除了包文件夹

方法一:

public static void ClearData(String Dir) {

    String sCommand = "rm -rf " + Dir + "*";
    Command command = new Command(0,sCommand);

    try {

        RootTools.getShell(true).add(command);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    } catch (RootDeniedException e) {
        e.printStackTrace();
    }

}

方法二:

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

tnx

编辑:我找到了解决方案:

public static void ClearData(String Dir) {

    String sCommand = "rm -rf " + Dir + "/*";
    Command command = new Command(0,sCommand);

    try {

        RootTools.getShell(true).add(command);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    } catch (RootDeniedException e) {
        e.printStackTrace();
    }

}

【问题讨论】:

    标签: android


    【解决方案1】:

    第二个是递归的经典例子。这值得学习,尤其是在您删除文件和文件夹时。

    不删除顶层的最简单方法是跟踪递归树中的深度,例如:

    public static boolean deleteDir(File dir, int depth) {
    

    每次调用 deleteDir 时,现在都添加“depth+1”的第二个参数,然后可以避免在深度为 0 时执行“dir.delete()”。

    一旦你得到了它,那么当你从你的程序中调用 deleteDir 时,你需要提供'0'的第二个参数,或者按名称调用参数。

    说了这么多,删除整个目录然后重新创建它可能更容易,但如果某些东西依赖于目录的存在,你就不想这样做了。

    【讨论】: