Question

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(); 
        } 
    } 
}
Was it helpful?

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.

OTHER TIPS

Here's an actually recursive method:

public void deleteDirectory(File startFile, FileFilter ignoreFilter) {
    if(startFile.isDirectory())
        for(File f : startFile.listFiles()) {
            deleteDirectory(f, ignoreFilter);
        }
    if(!ignoreFilter.accept(startFile)) {
        startFile.delete();
    }
}

Hand it a file filter set to return true for directories (see below) to make it not delete directories. You can also add exceptions for other files too

    FileFilter folderFilter = new FileFilter() {

        @Override
        public boolean accept(File paramFile) {
            return paramFile.isDirectory();
        }

    };

Simple,

Use isDirectory() to exclude it from being deleted.

Refer here: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#isDirectory()

First ever post, don't consider myself an expert but am stuck with 1.4...

Here's a recursive delete method that works well, deletes all files and subfolders within a parent folder then the parent folder itself, assumes the File being passed is a directory as it is in my case.

private void deleteTemp(File tempDir) {
    File[] a = (tempDir.listFiles());
        for (int i = 0; i < a.length; i++) {
            File b = a[i];
                if (b.isDirectory())
                    deleteTemp(b);

                b.delete();
        }

        tempDir.delete();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top