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();
}
}
In this
you are calling
after
This means that you are creating the file again after deleting File.delete() returns a boolean value.So if you want to check then do
System.out.println(index.delete());
if you gettrue
then this means that file is deletedfrom the comments given below,the updated answer is like this
If you have subfolders, you will find troubles with the Cemron answers. so you should create a method that works like this:
you can try as follows
If there are sub folders inside your folder you may need to recursively delete them.
Works like a Charm . For both folder and files . Salam :)
I like this solution the most. It does not use 3rd party library, instead it uses NIO2 of Java 7.
directry cannot simply delete if it has the files so you may need to delete the files inside first and then directory