Java File Path Delete deleteDir(File dir)

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

Description

Delete a directory and all of its contents.

License

Open Source License

Parameter

Parameter Description
dir The directory.

Exception

Parameter Description
IOException If something cannot be deleted.

Declaration

public static void deleteDir(File dir) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

public class Main {
    private static final File[] EMPTY_FILE_ARRAY = new File[0];

    /**//from  ww  w. j  a v a 2  s.  c o  m
     * Delete a directory and all of its contents.
     * 
     * @param dir
     *            The directory.
     * @throws IOException
     *             If something cannot be deleted.
     */
    public static void deleteDir(File dir) throws IOException {
        if (!dir.exists()) {
            return;
        }
        File[] files = listFiles(dir);
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) {
                deleteDir(file);
            } else {
                deleteFile(file);
            }
        }
        dir.delete();
    }

    /**
     * Utility method to list files but return an empty array instead of null for no results.
     * 
     * @param dir
     *            The directory.
     * @return The array of files.
     */
    public static File[] listFiles(File dir) {
        File[] files = dir.listFiles();
        if (files == null) {
            files = EMPTY_FILE_ARRAY;
        }
        return files;
    }

    /**
     * Delete file.
     * 
     * @param file
     *            The file.
     * @throws IOException
     *             If the file was not deleted.
     */
    private static void deleteFile(File file) throws IOException {
        boolean success = file.delete();
        if (!success) {
            throw new IOException("Could not delete " + file);
        }
    }

    /**
     * Delete a file or directory.
     * 
     * @param file
     *            The file or directory.
     * @throws IOException
     *             For IO Errors.
     */
    public static void delete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDir(file);
        } else {
            deleteFile(file);
        }
    }
}

Related

  1. deleteDir(File dir)
  2. deleteDir(File dir)
  3. deleteDir(File dir)
  4. deleteDir(File dir)
  5. deleteDir(File dir)
  6. deleteDir(File dir)
  7. deleteDir(File dir)
  8. deleteDir(File dir)
  9. deleteDir(File dir)