简体   繁体   English

删除 Android 内部存储中的目录

[英]Deleting directories within Android internal storage

In order to remove a directory within Android internal storage, this is the kind of code I use.为了删除 Android 内部存储中的目录,这是我使用的那种代码。

    val directory = getDir("myDirName", MODE_PRIVATE) // *1.

    if (directory.isDirectory()) {
        directory.delete()
    }

The first problem is that line *1 will create the directory in case it does not exist.第一个问题是 *1 行将创建目录以防万一它不存在。

Is there a way to actually know if a directory exists or not, without creating one if it does not?有没有办法真正知道目录是否存在,如果不存在则不创建目录?

Beside, I also noticed that this code is not working one hundred percent of the time.此外,我还注意到这段代码在 100% 的情况下都无法正常工作。

Is there a better way to remove a directory?有没有更好的方法来删除目录?

You could implement something like that:你可以实现类似的东西:

val directory = File("myDirName")

if (directory.exists()) {
    directory.delete()
}

this is a method which delete your app directory这是一种删除您的应用程序目录的方法

public boolean deleteRecursive(Context context,String filePath) {
        
        boolean result=false;

        //Create androiddeft folder if it does not exist
        File fileOrDirectory = new File(filePath);

        if (fileOrDirectory.isDirectory()) {
            for (File child : fileOrDirectory.listFiles()) {

                child.delete();
            }
        }else {
            log("Delete pdf","no directory found");
            return false;
        }

        if (fileOrDirectory.listFiles().length<2)
        {
            result=true;
        }else {
            result=false;
       }


       return  result;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM