Java Folder Delete emptyFolder(File folder)

Here you can find the source of emptyFolder(File folder)

Description

Removes a folder's contents

License

Open Source License

Parameter

Parameter Description
folder the java.io.File folder where the contents reside

Declaration

public static void emptyFolder(File folder) 

Method Source Code

//package com.java2s;
/*//from   w ww.ja va2s .  co  m
 *   This is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *    
 */

import java.io.File;

public class Main {
    /**
     * Removes a folder's contents
     * 
     * @param folder   the java.io.File folder where the contents reside
     */
    public static void emptyFolder(File folder) {
        deleteFolder(folder, true);
    }

    public static void deleteFolder(String folderPath) {
        deleteFolder(folderPath, false);
    }

    /**
     * Deletes a folder's contents
     * 
     * @param folderPath   the path to the folder to delete
     * @param keepRootFolder   if true, only the contents will be deleted, false will delete the folder itself as well
     */
    public static void deleteFolder(String folderPath, Boolean keepRootFolder) {

        File folderPathFiles = new File(folderPath);
        deleteFolder(folderPathFiles, keepRootFolder);

    }

    /**
     * Deletes a folder's contents
     * 
     * @param folder         the java.io.File folder to delete
     * @param keepRootFolder   if true, only the contents will be deleted, false will delete the folder itself as well
     */
    public static void deleteFolder(File folder, Boolean keepRootFolder) {

        if (!folder.isDirectory()) {
            return;
        }

        File[] files = folder.listFiles();

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteFolder(files[i], false);
            } else {
                files[i].delete();
            }
        }

        if (!keepRootFolder) {
            folder.delete();
        }

    }
}

Related

  1. emptyDerbyTestDirectory(final String derbyTestDirectory)
  2. emptyFile(final String urlFile)
  3. emptyFile(String srcFilename)
  4. emptyFolder(File dir)
  5. emptyFolder(File folder)
  6. emptyFolder(File folder, boolean ignoreCannotDel)
  7. emptyFolder(File toEmpty)
  8. emptyFolder(final File folder)
  9. emptyFolder(final File folder)