How to delete folders/files recursively in Java ?.
We do not have an direct API to remove folder and its child elements. However, it is not big deal to us to write
import java.io.File;
public class RemoveDir {
public static void main(String[] args) {
if(removeDir(new File("/tmp/a")))
{
System.out.println("Successfully removed Directory");
}
else
{
System.out.println("Not able to delete Directory, please refer exceptions");
}
}
public static boolean removeDir(File dir) {
try {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = removeDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
}
No comments:
Post a Comment