14

In my application I have written the code to delete the directory from drive but when I inspect the delete function of File it doesn't delete the file. I have written some thing like this

//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete(); 

the directoryis not in used still it is not able to delete the directory

Michael Borgwardt
  • 335,521
  • 76
  • 467
  • 706
Vipul
  • 2,539
  • 6
  • 23
  • 28
  • You have to delete the contents of the directory first -- however if it still doesn't work with an empty directory, it is because you're running on Windows, and the directory is locked because something is viewing the directory (or the current directory is set to the directory). – Luke Hutchison May 06 '19 at 23:39

5 Answers5

25

in Java, directory deletion is possible only for empty directory, which leads to methods like the following :

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}

This one will delete your folder, even if non-empty, without troubles (excepted when this directory is locked by OS).

Riduidel
  • 21,635
  • 13
  • 81
  • 178
  • not working...if (files.length==0) i.e. if path.listFiles() not contain any file, then unable to delete directory according to your code. – Rishav Singla Mar 06 '19 at 07:13
22

Why to invent a wheel with methods to delete recursively? Take a look at apache commons io. https://commons.apache.org/proper/commons-io/javadocs/api-1.4/

FileUtils.deleteDirectory(dir);

OR

FileUtils.forceDelete(dir);

That is all you need. There is also plenty of useful methods to manipulate files...

Daniel
  • 2,792
  • 2
  • 24
  • 44
Ilja S.
  • 1,101
  • 2
  • 12
  • 21
3

Looking at the docs:

If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Did you make sure that the directory is empty (no hidden files either) ?

user268396
  • 11,028
  • 28
  • 26
2

The directory must be empty to delete it. If it's not empty, you need to delete it recursively with File.listFiles() and File.delete()

iirekm
  • 7,787
  • 5
  • 34
  • 43
1

Two other possibilities (besides the directory not being empty):

  • The user which runs the java program does not have write/delete permission for the directory
  • The directory is used/locked by a different process (you write that it's not, but how have you confirmed this?)
Michael Borgwardt
  • 335,521
  • 76
  • 467
  • 706