Java Recursive Delete recursiveRemoveDir(File directory)

Here you can find the source of recursiveRemoveDir(File directory)

Description

del a directory recursively,that means delete all files and directorys.

License

Open Source License

Parameter

Parameter Description
directory the directory that will be deleted.

Exception

Parameter Description
Exception an exception

Declaration

public static void recursiveRemoveDir(File directory) throws Exception 

Method Source Code


//package com.java2s;
import java.io.File;

import java.io.IOException;

public class Main {
    /**/*from  w  ww. j  a va2 s  .  c o  m*/
     * del a directory recursively,that means delete all files and directorys.
     * 
     * @param directory
     *            the directory that will be deleted.
     * @throws Exception
     */
    public static void recursiveRemoveDir(File directory) throws Exception {
        if (!directory.exists()) {
            throw new IOException(directory.toString() + " do not exist!");
        }

        String[] filelist = directory.list();
        File tmpFile = null;
        for (int i = 0; i < filelist.length; i++) {
            tmpFile = new File(directory.getAbsolutePath(), filelist[i]);
            if (tmpFile.isDirectory()) {
                recursiveRemoveDir(tmpFile);
            } else if (tmpFile.isFile()) {
                try {
                    tmpFile.delete();
                } catch (Exception ex) {
                    throw new Exception(tmpFile.toString() + " can not be deleted " + ex.getMessage());
                }
            }
        }
        try {
            directory.delete();
        } catch (Exception ex) {
            throw new Exception(directory.toString() + " can not be deleted " + ex.getMessage());
        } finally {
            filelist = null;
        }
    }
}

Related

  1. recursivelyDelete(String loc)
  2. recursivelyDeleteEmptyDirectories(File fileToDelete)
  3. recursivelyDeleteEmptyParentDirectoriesUpToRoot(String path, String root)
  4. recursivelyDeleteFile(File path)
  5. recursiveRemoveDir(File dir)