Java Folder Delete clearDir(File dir)

Here you can find the source of clearDir(File dir)

Description

Deletes all sub-files and sub-directories in the given directory.

License

Open Source License

Parameter

Parameter Description
dir The directory to clear

Return

Whether the given directory is successfully cleared.

Declaration

public static boolean clearDir(File dir) 

Method Source Code

//package com.java2s;
/* ******************************************************************************
 * Copyright (c) 2006-2012 XMind Ltd. and others.
 * /*from   w  w w . j  a va  2s . c  o m*/
 * This file is a part of XMind 3. XMind releases 3 and
 * above are dual-licensed under the Eclipse Public License (EPL),
 * which is available at http://www.eclipse.org/legal/epl-v10.html
 * and the GNU Lesser General Public License (LGPL), 
 * which is available at http://www.gnu.org/licenses/lgpl.html
 * See http://www.xmind.net/license.html for details.
 * 
 * Contributors:
 *     XMind Ltd. - initial API and implementation
 *******************************************************************************/

import java.io.File;

public class Main {
    /**
     * Deletes all sub-files and sub-directories in the given directory.
     * 
     * @param dir
     *            The directory to clear
     * @return Whether the given directory is successfully cleared.
     */
    public static boolean clearDir(File dir) {
        if (!dir.isDirectory())
            return false;
        File[] files = dir.listFiles();
        if (files == null || files.length == 0)
            return true;
        boolean cleared = true;
        for (File sub : files) {
            cleared &= delete(sub);
        }
        return cleared;
    }

    /**
     * Deletes the given file and, if it is a directory, delete all its
     * sub-directories and sub-files.
     * 
     * @param f
     *            The file or directory to delete
     * @return Whether the given file or directory is successfully deleted.
     */
    public static boolean delete(File f) {
        if (f.isFile())
            return f.delete();
        else if (f.isDirectory()) {
            boolean b = clearDir(f);
            b &= f.delete();
            return b;
        } else
            return false;
    }
}

Related

  1. clearDir(File d)
  2. clearDir(File dir)
  3. clearDir(File dir)
  4. clearDir(File dir)
  5. clearFiles(File dir)
  6. clearFilesOnPath(String path)
  7. clearFolder(File f)