Java Delete Directory Recursively deleteDirectoryRecursive(File f)

Here you can find the source of deleteDirectoryRecursive(File f)

Description

Delete a directory and all of it's contents in a depth-first recursive manner.

License

Open Source License

Parameter

Parameter Description
f the directory to delete

Exception

Parameter Description
IOException if an error occurs

Declaration

public static void deleteDirectoryRecursive(File f) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

public class Main {
    /**//from w w w.jav  a  2  s . c o  m
     * Delete a directory and all of it's contents in a depth-first recursive manner.
     * @param f the directory to delete
     * @throws IOException if an error occurs
     */
    public static void deleteDirectoryRecursive(File f) throws IOException {
        if (f.isDirectory()) {
            for (File c : f.listFiles()) {
                deleteDirectoryRecursive(c);
            }
        }

        //once we have deleted all of a directories contents, we delete the directory
        delete(f);

    }

    /**
     * Delete a file.  This method will retry the delete up to 5 times, sleeping for one second between retries.
     * This is because sometimes, especially with smaller imports, the cleanup starts happening before vault has closed
     * all of it's file locks.  The retry behavior makes a best effort to properly cleanup when that happens.
     * @param f the file to delete
     * @throws IOException if the file can't be deleted.
     */
    private static void delete(File f) throws IOException {
        boolean isDeleted = f.delete();
        for (int i = 0; i < 4 && !isDeleted; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IOException("Failed to delete file: " + f, e);
            }
            isDeleted = f.delete();
        }

        if (!isDeleted) {
            throw new IOException("Failed to delete file: " + f);
        }
    }
}

Related

  1. deleteDirectoryRecursive(File directory)
  2. deleteDirectoryRecursively(File rootFile)
  3. deleteDirectoryRecursively(File toDelete)
  4. deleteDirectoryRecursivelyE(File dir)
  5. deleteDirectoryRecursivly(File directory)