Java Delete Directory deleteDirectory(File file)

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

Description

Delete a Directory.

License

Open Source License

Parameter

Parameter Description
file a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void deleteDirectory(File file) throws IOException, Exception 

Method Source Code


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

import java.io.File;

import java.io.IOException;

public class Main {
    /**/*from  w ww.  j a  va 2s .com*/
    * Delete a Directory.
    *
    * @param file
    * @throws IOException
    */
    public static void deleteDirectory(File file) throws IOException, Exception {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {
                file.setWritable(true);
                boolean b = file.delete();
                if (!b)
                    throw new IOException(
                            "Directory cannot be deleted : " + file.getAbsolutePath() + "\nCheck permissions.");

            } else {

                //list all the directory contents
                String files[] = file.list();

                for (String temp : files) {

                    //construct the file structure
                    File fileDelete = new File(file, temp);

                    //recursive delete
                    deleteDirectory(fileDelete);
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.setWritable(true);
                    boolean b = file.delete();
                    if (!b)
                        throw new IOException(
                                "Directory cannot be deleted : " + file.getAbsolutePath() + "\nCheck permissions.");
                }
            }

        } else {
            //if file, then delete it
            file.setWritable(true);
            boolean b = file.delete();
            if (!b)
                throw new IOException(
                        "File cannot be deleted : " + file.getAbsolutePath() + "\nCheck permissions.");
        }
    }
}

Related

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