How to delete all files and folders in one folder on Android

前端 未结 12 1344
广开言路
广开言路 2021-01-30 17:52

I use this code to delete all files:

File root = new File(\"root path\");
File[] Files = root.listFiles();
if(Files != null) {
    int j;
    for(j = 0; j < F         


        
12条回答
  •  忘掉有多难
    2021-01-30 17:52

    rm -rf was much more performant than FileUtils.deleteDirectory or recursively deleting the directory yourself.

    After extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.deleteDirectory.

    Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.deleteDirectory and only 1 minute with rm -rf.

    Here's our rough Java implementation to do that:

    // Delete directory given and all subdirectories and files (i.e. recursively).
    //
    static public boolean deleteDirectory( File file ) throws IOException, InterruptedException {
    
        if ( file.exists() ) {
    
            String deleteCommand = "rm -rf " + file.getAbsolutePath();
            Runtime runtime = Runtime.getRuntime();
    
            Process process = runtime.exec( deleteCommand );
            process.waitFor();
    
            return true;
        }
    
        return false;
    
    }
    

    Worth trying if you're dealing with large or complex directories.

提交回复
热议问题