Created
July 9, 2012 11:52
-
-
Save josefbetancourt/3076035 to your computer and use it in GitHub Desktop.
Use Groovy to find path of a file in a directory tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.transform.TypeChecked | |
/** | |
* search file according to its name in directory and subdirectories | |
*/ | |
@TypeChecked | |
class FileFind { | |
String basePath; // for unit testing | |
/** | |
* | |
* Find a file within a hierarchy given a path. | |
* | |
* @param basePath which folder to start the search | |
* @param targetPath the name or a sub path | |
* @return the path where the file was found | |
*/ | |
public String find(String basePath, String targetPath){ | |
def result = '' | |
String curPath = basePath + File.separator + targetPath | |
if(new File(curPath).exists()){ | |
result = curPath; | |
}else{ | |
result = searchUp(basePath, targetPath) | |
if(!result){ | |
result = searchDown(basePath, targetPath) | |
} | |
} | |
result | |
} | |
/** | |
* | |
* @param targetPath the name or a sub path | |
* @return the path where the file was found | |
*/ | |
public String find(String targetPath){ | |
def result = '' | |
String curDir = getCurrentPath() | |
find(curDir, targetPath) | |
} | |
/** depth first recursive search of sub directories */ | |
def searchDown(String startDir, String targetPath){ | |
def result = ""; | |
File curDir = new File("$startDir") | |
try{ | |
curDir.eachDirRecurse { File cur -> | |
def fp = new File(cur.path + File.separator + targetPath) | |
if(fp.exists()){ | |
result = fp | |
throw BREAK | |
} | |
} | |
}catch(BreakClosureException ex){ | |
// | |
} | |
result | |
} | |
/** Search for path in parent directories */ | |
def searchUp(String startDir, String targetPath){ | |
def result = ""; | |
File lastDir = new File(startDir) | |
def up = File.separator + '..' | |
File curDir = new File("$startDir$up") | |
try{ | |
while(curDir.getCanonicalPath() != lastDir.getCanonicalPath()){ | |
def fp = new File(curDir.path + File.separator + targetPath) | |
if(fp.exists()){ | |
result = fp | |
throw BREAK | |
} | |
lastDir = curDir | |
curDir = new File("${curDir.path}$up") | |
} | |
}catch(BreakClosureException ex){ | |
// | |
} | |
result | |
} | |
protected String getCurrentPath(){ | |
//return basePath ? basePath : new File(".").path | |
new File(".").path | |
} | |
final static BREAK = new BreakClosureException() // for exit out of closures | |
static class BreakClosureException extends Throwable { | |
public BreakClosureException() { | |
super() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment