Java File Path Delete deleteContents(File dirPath, List failures)

Here you can find the source of deleteContents(File dirPath, List failures)

Description

Recursive delete files.

License

Open Source License

Parameter

Parameter Description
dirPath directory of files to delete
failures the list of files that could not be deleted

Declaration

private static void deleteContents(File dirPath, List<File> failures) 

Method Source Code

//package com.java2s;
/**//from w  ww .ja v a 2  s . c  om
 * Distribution License:
 * JSword is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License, version 2.1 as published by
 * the Free Software Foundation. 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 Lesser General Public License for more details.
 *
 * The License is available on the internet at:
 *       http://www.gnu.org/copyleft/lgpl.html
 * or by writing to:
 *      Free Software Foundation, Inc.
 *      59 Temple Place - Suite 330
 *      Boston, MA 02111-1307, USA
 *
 * Copyright: 2005
 *     The copyright to this program is held by it's authors.
 *
 * ID: $Id$
 */

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**
     * Recursive delete files.
     * 
     * @param dirPath
     *            directory of files to delete
     * @param failures
     *            the list of files that could not be deleted
     */
    private static void deleteContents(File dirPath, List<File> failures) {
        String[] ls = dirPath.list();

        for (int idx = 0; idx < ls.length; idx++) {
            File file = new File(dirPath, ls[idx]);
            if (file.isDirectory()) {
                deleteContents(file, failures);
            }
            if (!file.delete()) {
                failures.add(file);
            }
        }
    }

    /**
     * Deletes a file or a directory and all of its contents
     * 
     * @param file
     *            or directory to delete
     * @return the list of files that could not be deleted
     */
    public static List<File> delete(File file) {
        List<File> failures = new ArrayList<File>();
        if (file.isDirectory()) {
            deleteContents(file, failures);
        }
        if (!file.delete()) {
            failures.add(file);
        }
        return failures;
    }
}

Related

  1. deleteAllFilesOnlyInDirectory(File startingDir)
  2. deleteAllFilesRecursively(String directoryName)
  3. deleteAndCreateFolder(String path)
  4. deleteBlankPath(String path)
  5. deleteChildDirectoriesExcept(File path, String... directoriesToSkip)
  6. deleteContentsOnly(final String srcPath)
  7. deleteDataFiles(final Collection paths)
  8. deleteDb(String path)
  9. deleteDir(File delDir)