Java Delete Empty Directory deleteEmptyDirectories(List dirs)

Here you can find the source of deleteEmptyDirectories(List dirs)

Description

Deletes empty directories recursively.

License

Open Source License

Declaration

public static int deleteEmptyDirectories(List<File> dirs) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by

import java.io.File;

import java.util.Iterator;
import java.util.List;

import java.util.logging.Logger;

public class Main {
    /** jdk1.4 logger */
    private static Logger logger = Logger.getLogger("de.axelwernicke.mypod.util");

    /**/*w w w  .  j  a v a 2 s  . c  om*/
     * Deletes empty directories recursively.
     */
    public static int deleteEmptyDirectories(List<File> dirs) {
        int dirsDeleted = 0;

        boolean success = false;
        File dir;

        // iterate over all dirs
        for (Iterator<File> dirIter = dirs.iterator(); dirIter.hasNext();) {
            dir = dirIter.next();

            // delete if dir exists and is empty
            if ((dir != null) && dir.exists() && (dir.list().length == 0)) {
                success = dir.delete();
                if (success) {
                    dirsDeleted++;
                }
            }
        }

        return dirsDeleted;
    }

    /**
     * Deletes a file.
     * If file can not deleted now, its scheduled to be deleted on myPod exit
     *
     * @param file to be deleted
     * @return true, if file was successfully deleted or scheduled to be deleted on exit.
     */
    public static boolean delete(File file) {
        logger.entering("de.axelwernicke.mypod.util.FileUtils", "delete");

        boolean success = false;

        try {
            if (file.canRead() && file.canWrite()) {
                boolean deleted = file.delete();
                if (!deleted) {
                    file.deleteOnExit();
                }

                success = true;
            }
        } catch (Exception e) {
            logger.warning("Exception raised: " + e.getMessage());
            e.printStackTrace();
        }

        logger.exiting("de.axelwernicke.mypod.util.FileUtils", "delete");

        return success;
    }
}

Related

  1. deleteEmptyChildren(java.io.File file)
  2. deleteEmptyDir(File directory)
  3. deleteEmptyDir(File file)
  4. deleteEmptyDirectory(File fileOrDirectory)
  5. deleteEmptyDirectoryRecursive(File directory)
  6. deleteEmptyDirectoryRecursive(File directory)
  7. deleteEmptyDirs(File dir)