1

I have an android app that needs to be able to delete large directories quickly. I know that when an app has a lot of data, the OS is able to clear the data app instantly (from app settings). However, when I manually try to delete a directory with a background task, looping through the folders and deleting the files takes a long time (several minutes) to complete. How does the OS delete data so quickly, but when it is done in code, it takes such a long time? Is there a faster way to do it?

    private boolean deleteDirectory(String dir) {
        Log.d(TAG, "deleteDirectory");
        // If dir is not separated from the end of the character to the file, the file is automatically added delimiter
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // If dir corresponding file does not exist or is not a directory, then exit
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            return false;
        }
        boolean flag = true;
        // delete all the files in the folder, including subdirectories
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                final int count = i;
                // delete subfolders
                if (files[i].isFile()) {
                    try {
                        FileUtils.forceDelete(files[count]);
                    } catch (IOException e) {
                        Log.e(TAG, e.getLocalizedMessage(), e);
                    }

                } else if (files[i].isDirectory()) {

                    flag = deleteDirectory(files[i]
                            .getAbsolutePath());
                }
                if (dir == path) {
                    Log.d(TAG, "delete dir: " + dirFile);
                    curPosi++;
                    publishProgress(curPosi);
                }
            }
        }
        if (!flag) {
            return false;
        }
        // delete the current directory

        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }
mattfred
  • 2,689
  • 1
  • 22
  • 38

1 Answers1

0

I'm pretty sure that the OS deletes it at a lower level, by accessing the actual filesystem. Either way, you should try using the Apache Commons FileUtils library -- it has a deleteDirectory() method, which will save you a lot of recursion.

Alternatively, you can actually try to run "rm -rf" directly, using runtime.exec(), but I'm not sure that permissions it would require. Here's an example

user496854
  • 6,461
  • 10
  • 47
  • 84