Thursday, July 23, 2009

Remove Folder in Java

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;
}
}

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More