Breaking News
Home / Java / Java Snippets / Find Files in Directory based on Extension

Find Files in Directory based on Extension

Find file in directoryHow about finding files of a given type (extension) in a given folder? The following snippets shows how to do so, it list all the files in the directory, then using Regex pattern it tries to match the extension within the file name. If a match is found, it adds to the list.

The Snippet

 

Output

Run the snippet with the following (Trying to find all image files with the extension jpg).

java com.livrona.snippets.io.FileFinder c:/images jpg

DEBUG>[FileFinder]-checking file  IMG_0002.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0002.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  IMG_0007.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0007.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  IMG_0010.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0010.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  IMG_0011.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0011.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  IMG_0014.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0014.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  IMG_0016.jpgfor jpg pattern  match
DEBUG>[FileFinder]-IMG_0016.jpg has valid pattern. adding to scanned list
DEBUG>[FileFinder]-checking file  RssMap.xmlfor jpg pattern  match
DEBUG>[FileFinder]-RssMap.xml does NOT have valid pattern.
DEBUG>[FileFinder]-checking file  test.pdffor jpg pattern  match
DEBUG>[FileFinder]-test.pdf does NOT have valid pattern.
DEBUG>[FileFinder]-checking file  urllist.txtfor jpg pattern  match
DEBUG>[FileFinder]-urllist.txt does NOT have valid pattern.
DEBUG>[FileFinder]-checking file  water.pdffor jpg pattern  match
DEBUG>[FileFinder]-water.pdf does NOT have valid pattern.
DEBUG>[FileFinder]-File : 1 – > C:imagesIMG_0002.jpg
DEBUG>[FileFinder]-File : 2 – > C:imagesIMG_0007.jpg
DEBUG>[FileFinder]-File : 3 – > C:imagesIMG_0010.jpg
DEBUG>[FileFinder]-File : 4 – > C:imagesIMG_0011.jpg
DEBUG>[FileFinder]-File : 5 – > C:imagesIMG_0014.jpg
DEBUG>[FileFinder]-File : 6 – > C:imagesIMG_0016.jpg
INFO>[FileFinder]-Total files found : 6

 [pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Advertisment ad adsense adlogger