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();
}
}
Create directory -
Delete directory -
Refer this resource for detailed explanation - delete directory.
Most of answers (even recent) referencing JDK classes rely on
File.delete()
but that is a flawed API as the operation may fail silently.The
java.io.File.delete()
method documentation states :As replacement, you should favor
Files.delete(Path p)
that throws anIOException
with a error message.The actual code could be written such as :
In JDK 7 you could use
Files.walkFileTree()
andFiles.deleteIfExists()
to delete a tree of files.In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.
Using Apache Commons-IO, it is following one-liner:
This is (slightly) more performant than
FileUtils.deleteDirectory
.Some of these answers seem unnecessarily long:
Works for sub directories too.