Find a list of files with certain extension in a folder using Java   #


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: 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); } } }

Loading Please Wait...