Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use Groovy to find path of a file in a directory tree
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