Search code examples
javafileutils

recursively delete a folder in java


I already have a code that works, but I don't want it to actually delete the temp folder if possible. I am using the apache fileutils. Also does anyone know how to exclude folders from being deleted?

public class Cleartemp { 
    static String userprofile = System.getenv("USERPROFILE");
    public static void main(String[] args) { 
        try { 
            File directory = new File(userprofile+"\\AppData\\Local\\Temp");  
            // 
            // Deletes a directory recursively. When deletion process is fail an 
            // IOException is thrown and that's why we catch the exception. 
            // 
            FileUtils.deleteDirectory(directory); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
}

Solution

  • How about FileUtils.cleanDirectory ? It cleans a directory without deleting it.

    You could also use Apache Commons DirectoryWalker if you need some filtering logic. One of the examples on the page includes FileCleaner implementation.