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();
}
}
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();
}
}
This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in
listFiles()
.Update, to avoid following symbolic links:
Remove it from else part
You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().
This is the best solution for
Java 7+
:You can use this function
Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.
Use something like:
Then you should be able to delete the folder by using
index.delete()
Untested!