import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DeleteEmptyFolder {
public static void main(String[] args) throws IOException {
deleteEmptyFolders("C:\\temp");
}
public static void deleteEmptyFolders(String folderName) throws FileNotFoundException {
File aStartingDir = new File(folderName);
List<File> emptyFolders = new ArrayList<File>();
findEmptyFoldersInDir(aStartingDir, emptyFolders);
List<String> fileNames = new ArrayList<String>();
for (File f : emptyFolders) {
String s = f.getAbsolutePath(); fileNames.add(s);
}
for (File f : emptyFolders) {
boolean isDeleted = f.delete();
if (isDeleted) {
System.out.println(f.getPath() + " deleted");
}
}
}
public static boolean findEmptyFoldersInDir(File folder, List<File> emptyFolders) {
boolean isEmpty = false;
File[] filesAndDirs = folder.listFiles();
List<File> 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;
}
}