Sunday, September 27, 2015

Find all empty folders

problem
I was cleaning up my computer and kept running into empty directories. So I created this small Java utility to find empty folders that I could delete.


code
package findemptyfolders; import java.io.*; import java.util.*; /** * Starting from a top folder, walks through all subdirectories and * outputs a list of directories are that are empty all the way down. * @author Mac */ public class FindEmptyFolders { static HashMap<String, String> map = new HashMap<String, String>(); static HashMap<String, LinkedList<String>> reverseIndex = new HashMap<String, LinkedList<String>>(); /** * @param args the command line arguments */ public static void main(String[] args) { File file = new File("D:/Temp"); walkDir(file); removeChildrenOfEmptyParents(); printResults(); } private static void removeChildrenOfEmptyParents() { for (String parent : reverseIndex.keySet()) { if (map.containsKey((parent))) { for (String child : reverseIndex.get(parent)) { map.remove(child); } } } } private static void printResults() { System.out.println(""); for (Map.Entry<String, String> kvp : map.entrySet()) { System.out.printf("Empty all the way down: Child:%s Parent:%s\r\n", kvp.getKey(), kvp.getValue()); } } public static boolean walkDir(File dir) { boolean hasFiles = false; try { for (File f : dir.listFiles()) { if (f.isFile()) { hasFiles = true; continue; } if (walkDir(f)) hasFiles = true; } if (!hasFiles) { //If you want to programmatically delete the empty folder do that right here updateMap(dir.getAbsolutePath(), dir.getParentFile().getAbsolutePath()); } } catch (Exception ex) { System.out.println("Error happened for " + dir.getName()); System.out.println(ex); } return hasFiles; } private static void updateMap(String dirPath, String dirParentPath) { if (reverseIndex.containsKey(dirParentPath)) { reverseIndex.get(dirParentPath).add(dirPath); } else { LinkedList<String> list = new LinkedList<String>(); list.add(dirPath); reverseIndex.put(dirParentPath, list); } map.put(dirPath, dirParentPath); } }

No comments:

Post a Comment

There was an error in this gadget