Recursively searching for similar files on file-system in groovy

13 / Dec / 2010 by Vishal Sahu 0 comments

Hi,

In my recent grails project, i needed to find the existence of particular files on file system.
I needed to search in a directory and all of its subdirectories and look into them if the files with the given format exists in it or not.
If the files exists, then it should return the complete path of the file. I searched a lot and came across a simple code to do so and thought of sharing it with you.

Lets we want to search all the .jpeg files in a directory ‘docs’ in my home folder(i am using ubuntu).

The groovy code to search files is as :-

List filesPath=[]
File fileDir=new File("/home//docs/")
fileDir.eachDirRecurse() { dir ->  
    dir.eachFileMatch(~/.*.jpeg/) { file ->  
        filesPath.add(file.path  )
    }  
}  

So, this code will list all the files with extension as ‘.jpeg’ in docs directory as well as in its subdirectories.

This works for me. Hope it helps!!!.

Cheers!!

Vishal Sahu
vishal@intelligrape.com

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -