Java Delete Directory deleteDirectory(String fileName)

Here you can find the source of deleteDirectory(String fileName)

Description

delete Directory

License

Open Source License

Declaration

public static void deleteDirectory(String fileName) 

Method Source Code

//package com.java2s;
// Use of this software is governed by the GPLv3 license

import java.io.File;

import java.io.IOException;

public class Main {
    public static void deleteDirectory(String fileName) {

        File directory = new File(fileName);

        //make sure directory exists
        if (!directory.exists()) {
            //do nothing
        } else {/*from ww  w.j  a va2 s .co  m*/

            try {
                deleteResursive(directory);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteResursive(File file) throws IOException {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {
                file.delete();
            } 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
                    deleteResursive(fileDelete);
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.delete();
                }
            }

        } else {
            //if file, then delete it
            file.delete();
        }
    }
}

Related

  1. deleteDirectory(String directoryName)
  2. deleteDirectory(String directoryName)
  3. deleteDirectory(String dirName)
  4. deleteDirectory(String dirName)
  5. deleteDirectory(String dirname, boolean recursive)
  6. deleteDirectory(String folder)
  7. deleteDirectory(String name)
  8. deleteDirectoryContent(final String strDir)
  9. deleteDirectoryContents(File directory)