javafile-iodelete-directory

How to delete a folder with files using Java


I want to create and delete a directory using Java, but it isn't working.

File index = new File("/home/Work/Indexer1");
if (!index.exists()) {
    index.mkdir();
} else {
    index.delete();
    if (!index.exists()) {
        index.mkdir();
    }
}

Solution

  • Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.

    Use something like:

    String[] entries = index.list();
    for (String s : entries) {
        File currentFile = new File(index.getPath(), s);
        currentFile.delete();
    }
    

    Then you should be able to delete the folder by using index.delete() Untested!