Java File Delete delete(File file)

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

Description

Recursively delete a file or directory.

License

Open Source License

Exception

Parameter Description
IOException if the file or directory couldn't be deleted. Unlike File.delete,which just returns false.

Declaration

public static void delete(File file) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;

import java.io.FilenameFilter;
import java.io.IOException;

public class Main {
    /**/*from w  w  w  .  ja  va 2  s . co  m*/
     * Recursively delete a file or directory.
     * 
     * @throws IOException
     *           if the file or directory couldn't be deleted. Unlike File.delete,
     *           which just returns false.
     */
    public static void delete(File file) throws IOException {
        if (file.exists() && file.isDirectory()) {
            for (File child : listFiles(file)) {
                delete(child);
            }
        }

        if (file.exists() && !file.delete()) {
            throw new IOException("Could not delete " + file);
        }
    }

    /**
     * Recursively delete a file or directory.
     * A description of any files or directories
     * that can not be deleted will be added to failures
     * if failures is non-null.
     * This method tries to delete as much as possible.
     */
    public static void delete(File file, StringBuilder failures) {
        if (file.exists() && file.isDirectory()) {
            for (File child : listFiles(file)) {
                delete(child, failures);
            }
        }

        if (file.exists() && !file.delete()) {
            if (failures != null) {
                failures.append("Could not delete ").append(file).append('\n');
            }
        }
    }

    /**
     * Basically just like {@link File#listFiles()} but instead of returning null
     * returns an empty array. This fixes bug 43729
     */
    public static File[] listFiles(File dir) {
        File[] result = dir.listFiles();
        if (result == null) {
            result = new File[0];
        }
        return result;
    }

    /**
     * Basically just like {@link File#listFiles(FilenameFilter)} but instead of returning null
     * returns an empty array. This fixes bug 43729
     */
    public static File[] listFiles(File dir, FilenameFilter filter) {
        File[] result = dir.listFiles(filter);
        if (result == null) {
            result = new File[0];
        }
        return result;
    }
}

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)