Java Folder Delete emptyFolder(File dir)

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

Description

Remove all files from a folder, return false if at least one file could not be deleted.

License

Open Source License

Parameter

Parameter Description
dir Folder to empty

Return

false if at least one file could not be deleted, true otherwise.

Declaration

public static boolean emptyFolder(File dir) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Firestar Software, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   w  w w  . jav  a2s. c o  m
 *     Firestar Software, Inc. - initial API and implementation
 *
 * Author:
 *     Gabriel Oancea
 *
 *******************************************************************************/

import java.io.*;

public class Main {
    /**
     * Remove all files from a folder, return false if at least one file could not be deleted. It WILL attempt to remove
     * all files, even if some fail. Does NOT attempt to remove or empty and sub-folders.
     * 
     * @param dir Folder to empty
     * @return false if at least one file could not be deleted, true otherwise.
     */
    public static boolean emptyFolder(File dir) {
        if (dir == null)
            throw new IllegalArgumentException(
                    "Null path in FileUtil.emptyFolder()");
        if (!dir.isDirectory())
            throw new IllegalArgumentException("Invalid path "
                    + dir.getAbsolutePath()
                    + ": not a directory, in FileUtil.emptyFolder()");
        boolean ok = true;
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length && ok; i++) {
            if (files[i].isFile())
                ok &= files[i].delete();
        }
        return ok;
    }
}

Related

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