Java File Delete delete(File file)

Here you can find the source of delete(File file)

Description

Deletes a file or a directory and all of its contents

License

Open Source License

Parameter

Parameter Description
file or directory to delete

Return

the list of files that could not be deleted

Declaration

public static List<File> delete(File file) 

Method Source Code

//package com.java2s;
/**//from   ww  w .java 2s. com
 * 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 {
    /**
     * 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;
    }

    /**
     * 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);
            }
        }
    }
}

Related

  1. delete(File file)
  2. delete(File file)
  3. delete(File file)
  4. delete(File file)
  5. delete(File file)
  6. delete(File file)
  7. delete(File file)
  8. delete(File file)
  9. delete(File file)