Java Delete Folder deleteFolder(File folder)

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

Description

Deletes the folder and all of its contents

License

Open Source License

Parameter

Parameter Description
folder the folder to delete

Return

true if successful

Declaration

public static boolean deleteFolder(File folder) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Gabriel Skantze./*from w  w w. j  av a 2  s.  c  om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Gabriel Skantze - initial API and implementation
 ******************************************************************************/

import java.io.File;

import java.util.List;

public class Main {
    /**
     * Deletes the folder and all of its contents
     * @param folder the folder to delete
     * @return true if successful
     */
    public static boolean deleteFolder(File folder) {
        if (!folder.exists())
            return false;
        if (!folder.isDirectory())
            return false;
        if (!cleanFolder(folder))
            return false;
        return folder.delete();
    }

    /**
     * Deletes all the contents of the folder (but preserves the empty folder)
     * @param folder the folder to clean
     * @return true if successful
     */
    public static boolean cleanFolder(File folder) {
        if (!folder.isDirectory())
            return false;
        File[] files = folder.listFiles();
        boolean success = true;
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    success = deleteFolder(f) && success;
                } else {
                    success = f.delete() && success;
                }
            }
        }
        return success;
    }

    public static void listFiles(String directoryName, List<String> files,
            String pattern) {
        File directory = new File(directoryName);

        // get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList) {
            if (file.isFile()) {
                if (file.getName().matches(pattern))
                    files.add(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                listFiles(file.getAbsolutePath(), files, pattern);
            }
        }
    }
}

Related

  1. deleteFolder(File file)
  2. deleteFolder(File file)
  3. deleteFolder(File file)
  4. deleteFolder(File file, boolean deleteParent)
  5. deleteFolder(File file, boolean withCurrentFolder)
  6. deleteFolder(File folder)
  7. deleteFolder(File folder)
  8. deleteFolder(File folder)
  9. deleteFolder(File folder)