Java File Path Delete deleteTree(final File path)

Here you can find the source of deleteTree(final File path)

Description

Delete all files recursively within tree.

License

Open Source License

Parameter

Parameter Description
path root of tree to delete.

Declaration

public static void deleteTree(final File path) 

Method Source Code


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

import java.io.File;

public class Main {
    /**/*from  ww  w.  j  av  a2 s  . c  o  m*/
     * Delete all files recursively within tree.
     * 
     * @param path
     *            root of tree to delete.
     */
    public static void deleteTree(final File path) {
        if (path.exists()) {
            if (path.isDirectory()) {
                File[] files = path.listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isDirectory()) {
                        deleteTree(files[i]);
                    } else {
                        files[i].delete();
                    }
                }
                files = null;
            } else {
                path.delete();
            }
        }

        deleteEmptyParents(path);
    }

    /**
     * Delete path and any empty parent directories.
     * 
     * @param path
     *            directory to start in.
     */
    public static void deleteEmptyParents(final File path) {
        deleteEmptyParents(path, null);
    }

    /**
     * Delete path and any empty parent directories up to the stopAt point.
     * 
     * @param path
     *            direcotry to start in
     * @param stopAt
     *            directory to stop at
     */
    public static void deleteEmptyParents(final File path, final File stopAt) {
        File parent = path;
        // Loop while parent is not null and we are not yet at the stopAt point
        while (parent != null && !parent.equals(stopAt)) {
            try {
                parent.delete();
                parent = parent.getParentFile();
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }
}

Related

  1. deleteSelectedFilesFromDirectory(final String directoryPath, final List filesList)
  2. deleteSubfiles(String publishTemppath)
  3. deleteTemp(String tempPath)
  4. deleteTempDataFile(String dataFilePath)
  5. deleteTempFile(String sourceFilePath)
  6. deleteWallpaper(String file_name, Map dimmensions, String basepath, List resolution_directories)
  7. delFile(String filePath)
  8. delFile(String filePath, String fileName)
  9. delFile(String filePathAndName)