Java File Path Delete deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories)

Here you can find the source of deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories)

Description

Delete a directories contents.

License

Open Source License

Parameter

Parameter Description
directoryPath Path of directory whose contents to delete
deleteChildDirectories True to recursively delete all directories

Exception

Parameter Description
Exception an exception

Declaration

public static boolean deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories)
        throws Exception 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    /**/*from   w  ww .  j ava2s . c  o m*/
     * Delete a directories contents. If deleteChildDirectories is true, then recursively
     * delete all child directories also, otherwise just delete the files.
     *
     * @param directoryPath     Path of directory whose contents to delete
     * @param deleteChildDirectories    True to recursively delete all directories
     * @throws Exception
     */
    public static boolean deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories)
            throws Exception {
        final String eLabel = "FileUtils.deleteDirectoryContents: ";
        try {
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                return false;
            }
            if (!directory.isDirectory()) {
                throw new Exception("Not a directory!!!");
            }
            File[] children = directory.listFiles();
            for (int i = 0; i < children.length; i++) {
                if (children[i].isFile()) {
                    if (!children[i].delete()) {
                        throw new Exception("Could not delete file: " + children[i].getName());
                    }
                } else {
                    if (deleteChildDirectories) {
                        deleteDirectoryContents(children[i].getPath(), true);
                    }
                    if (!children[i].delete()) {
                        throw new Exception("Could not delete directory: " + children[i].getName());
                    }
                }
            }
            return true;
        } catch (Exception e) {
            throw new Exception(eLabel + e);
        }
    }
}

Related

  1. deleteDirectory(String path)
  2. deleteDirectory(String sPath)
  3. deleteDirectoryAndContents(final File srcPath)
  4. deleteDirectoryAndContentsRecursive(final File srcPath, final boolean deleteSrcDir)
  5. deleteDirectoryContents(File path)
  6. deleteDirectoryIncludeContent(String folderPath)
  7. deleteDirectoryInternal(File path)
  8. deleteDirectoryRecursively(File path)
  9. deleteDirectoryRecursivly(String path)