Thursday, November 05, 2009

Delete files and directories recursively in Java

This post will teach you how to delete files and directories in Java recursively. There is nothing special in this post but I’m sure this will be useful especially for those who are just starting out their programming career in Java.



boolean deleteRecursively(final File file) {
if (file.exists()) {
final File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteRecursively(files[i]);
}
else {
files[i].delete();
}
}
}
return (file.delete());
}

This code was not tested. Please read the Java 6 File API documentation [here] for more information.


"Confidence means non-paralysis, a willingness to act, and act decisively, to start new things and cut failing ventures off." - Tom Peters

No comments: