Wednesday, July 8, 2009

Recursively deleting empty folders

I needed to delete empty folders as part of my work. Empty Folders by definition are those which have no files and only empty directories.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class DeleteEmptyFolder {

/**
* @param args
*/
public static void main(String[] args)throws IOException {
deleteEmptyFolders("C:\\d00");
}


public static void deleteEmptyFolders(String folderName)
throws FileNotFoundException {
File aStartingDir = new File(folderName);
List emptyFolders = new ArrayList();
findEmptyFoldersInDir(aStartingDir, emptyFolders);
List fileNames = new ArrayList();
for (File f : emptyFolders) {
String s = f.getAbsolutePath();
fileNames.add(s);
System.out.println(s);
}

// return fileNames;
System.out.println("Total Number of Folder :: " + fileNames.size());
System.out.println("Deleting all folders");
for (File f : emptyFolders) {
boolean isDeleted = f.delete();
System.out.println(f.getPath() + " deleted = " + isDeleted);
}
}


public static boolean findEmptyFoldersInDir(File folder, List emptyFolders) {
boolean isEmpty = false;

File[] filesAndDirs = folder.listFiles();
List filesDirs = Arrays.asList(filesAndDirs);
if (filesDirs.size() == 0) {
isEmpty = true;
}

if(filesDirs.size() > 0) {
boolean allDirsEmpty = true;
boolean noFiles = true;
for (File file : filesDirs) {
if (!file.isFile()) {
boolean isEmptyChild = findEmptyFoldersInDir(file, emptyFolders);
if (!isEmptyChild) {
allDirsEmpty = false;
}
}
if (file.isFile()) {
noFiles = false;
}


}

if(noFiles == true && allDirsEmpty == true) {
isEmpty = true;
}

}

if(isEmpty){
emptyFolders.add(folder);
}

return isEmpty;
}



}

No comments:

Post a Comment