DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Yale has posted 1 posts at DZone. View Full User Profile

Recursively Delete Everything In A Directory Except Things With Certain Extensions (Groovy)

09.26.2008
| 5051 views |
  • submit to reddit
        I use this when I want to prune a copy of my source tree for faster text searching.

def root = "C:\\SEARCH_INDEX";
def exts = new ArrayList<String>();

exts.add("java");
exts.add("properties");
exts.add("xml");
exts.add("xhtml");
exts.add("jsp");
exts.add("html");
exts.add("js");

new File(root).eachFileRecurse { fn->
   
     if (fn.isFile()) {
            def ext = fn.name.substring(fn.name.lastIndexOf('.')+1, fn.name.length());
            
            if (!exts.contains(ext)) {
                println "kill " + fn
            try {
                fn.delete()   
            } catch (Exception e) {
                println e   
            }

            }
        }
}