Delete all files in directory (but not directory) - one liner solution

前端 未结 11 1195
不思量自难忘°
不思量自难忘° 2020-12-12 11:38

I want to delete all files inside ABC directory.

When I tried with FileUtils.deleteDirectory(new File(\"C:/test/ABC/\")); it also deletes folder ABC.

11条回答
  •  囚心锁ツ
    2020-12-12 11:55

    rm -rf was much more performant than FileUtils.cleanDirectory.

    Not a one-liner solution but after extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.cleanDirectory.

    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.cleanDirectory 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 clearDirectory( 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();
    
            file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.
    
            return true;
        }
    
        return false;
    
    }
    

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

提交回复
热议问题