Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 309
Mr.G Avatar asked Nov 29 '13 09:11

Mr.G


People also ask

Can you delete a directory with files in Java?

Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder. Then you should be able to delete the folder by using index.

How can we delete all files in a directory in Java?

You can use the FileUtils. cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself. To delete a directory recursively and everything in it, you can use the FileUtils. deleteDirectory() method.

What method is used to delete a folder in Java?

Java File delete() method can be used to delete files or empty directory/folder in java.


3 Answers

Just a one-liner.

import org.apache.commons.io.FileUtils;

FileUtils.deleteDirectory(new File(destination));

Documentation here

like image 182
Barry Knapp Avatar answered Oct 22 '22 07:10

Barry Knapp


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!

like image 29
Cemron Avatar answered Oct 22 '22 07:10

Cemron


This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

Update, to avoid following symbolic links:

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}
like image 108
Jeff Learman Avatar answered Oct 22 '22 07:10

Jeff Learman