Java Delete Directory deleteDirectory(File directory)

Here you can find the source of deleteDirectory(File directory)

Description

delete Directory

License

Apache License

Declaration

public static void deleteDirectory(File directory) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {
    public static void deleteDirectory(File directory) throws IOException {
        if (!directory.exists())
            return;
        cleanDirectory(directory);/*from w  ww.  jav  a 2 s.  c  o  m*/
        if (!directory.delete()) {
            String message = "Unable to delete directory " + directory + ".";
            throw new IOException(message);
        } else {
            return;
        }
    }

    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }
        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }
        File files[] = directory.listFiles();
        if (files == null)
            throw new IOException("Failed to list contents of " + directory);
        IOException exception = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            try {
                forceDelete(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception)
            throw exception;
        else
            return;
    }

    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            if (!file.exists())
                throw new FileNotFoundException("File does not exist: " + file);
            if (!file.delete()) {
                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }
}

Related

  1. deleteDirectory(File directory)
  2. deleteDirectory(File directory)
  3. deleteDirectory(File directory)
  4. deleteDirectory(File directory)
  5. deleteDirectory(File directory)
  6. deleteDirectory(File directory)
  7. deleteDirectory(File directory, boolean ignoreErrors)
  8. deleteDirectory(File f)
  9. deleteDirectory(File f)