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

package com.livrona.snippets.io;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.livrona.snippets.util.Log;

/**
 * A simple snippet that finds all the files of a given extension in a target
 * folder.
 * 
 * @author java4learners
 * 
 */
public class FileFinder {

	private static final Log log = new Log(FileFinder.class);

	/**
	 * Find Files based on extension
	 * 
	 * @param targetDir
	 * @param extension
	 * @return
	 */
	private List<File> findFiles(String targetDir, String extension) {
		List<File> scannedFiles = new ArrayList<File>();
		// open handle to the directory
		File dir = new File(targetDir);

		// check it is a directory
		if (dir.isDirectory()) {
			// get list of files
			File[] files = dir.listFiles();
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				// get file name
				String fileName = file.getName();
				log.debug("checking file  " + fileName
						+ "for " +  extension + " pattern  match");
				// is file .extension matching
				Pattern p = Pattern.compile("^.*." + extension + "$");
				Matcher m = p.matcher(fileName);

				if (m.matches()) {
					log.debug(fileName
							+ " has valid pattern. adding to scanned list");
					scannedFiles.add(file);
				} else {
					log.debug(fileName + " does NOT have valid pattern. ");
				}
			}
		}
		return scannedFiles;
	}

	/**
	 * Test method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length != 2) {
			System.out
					.println("Usage: java com.livrona.snippets.io.FileFinder <Folder> <Extension>");
			System.exit(0);
		}

		try {
			// input
			String targetDir = args[0];
			String extension = args[1];
			FileFinder finder = new FileFinder();
			List<File> files = finder.findFiles(targetDir, extension);
			Iterator<File> it = files.iterator();
			int i = 0;
			while (it.hasNext()) {
				File file = it.next();
				i++;
				log.debug("File : " + i + " - > " + file.getAbsolutePath());

			}
			log.info("Total files found : " + files.size());
		} catch (Exception e) {
			log.error("Failed list files in the dir: " + e.getMessage(), e);
		}
	}
}

 

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 …

Leave a Reply