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();
}
}
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.
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.
Java File delete() method can be used to delete files or empty directory/folder in java.
Just a one-liner.
import org.apache.commons.io.FileUtils;
FileUtils.deleteDirectory(new File(destination));
Documentation here
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!
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With