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.m
In JDK 7 you could use Files.walkFileTree()
and Files.deleteIfExists()
to delete a tree of files. (Sample: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)
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.
I prefer this solution on java 8:
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
From this site: http://www.baeldung.com/java-delete-directory
Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.
com.google.common.io.MoreFiles.deleteRecursively(
file.toPath(),
RecursiveDeleteOption.ALLOW_INSECURE
) ;
(This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)
You can make recursive call if sub directories exists
import java.io.File;
class DeleteDir {
public static void main(String args[]) {
deleteDirectory(new File(args[0]));
}
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}
}
Some of these answers seem unnecessarily long:
if (directory.exists()) {
for (File file : directory.listFiles()) {
file.delete();
}
directory.delete();
}
Works for sub directories too.
My basic recursive version, working with older versions of JDK:
public static void deleteFile(File element) {
if (element.isDirectory()) {
for (File sub : element.listFiles()) {
deleteFile(sub);
}
}
element.delete();
}