Sunday 26 May 2019

Java: Search for files in a folder


Using 'File.listFiles(FileNameFilter filter)' method, you can check whether given files exist in a directory or not.

private File[] getMatchedFiles(File file) {

         File[] matches = file.listFiles(new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                           return fileNames.contains(name);

                  }
         });

         return matches;
}

Since listFiles function do not traverse the sub directories, we need to traverse sub directories explicitly to find all the matched files.

Find the below working application.

FileSearch.java
package com.sample.app;

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FileSearch {

 private File file;
 private List<String> fileNames;
 private Set<String> matchedFiles;

 public FileSearch(String folderPath, List<String> fileNames) {
  if (fileNames == null || fileNames.isEmpty()) {
   throw new IllegalArgumentException("fileNames can't be null or empty");
  }

  File file = new File(folderPath);
  if (!file.exists() || !file.isDirectory()) {
   throw new IllegalArgumentException("File is not exists or not a directory");
  }

  this.file = file;
  this.fileNames = fileNames;
  this.matchedFiles = new HashSet<> ();
 }

 private File[] getMatchedFiles(File file) {

  File[] matches = file.listFiles(new FilenameFilter() {
   public boolean accept(File dir, String name) {
    return fileNames.contains(name);

   }
  });

  return matches;
 }


 private void recursiveSearch(File path) {

  addMatchedFiles(getMatchedFiles(path));
  for (File file : path.listFiles()) {
   if (file.isDirectory()) {
    recursiveSearch(file);
   }
  }
 }

 
 private void addMatchedFiles(File[] files) {
  for (File file : files) {
   matchedFiles.add(file.getName());
  }
 }

 public Set<String> getMatchedFiles(){
  recursiveSearch(this.file);
  return matchedFiles;
 }
  
}


App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Set;

public class App {

 public static void main(String args[]) {

  FileSearch fileSearch = new FileSearch("/Users/krishna/Documents/TechnicalDocuments",
    Arrays.asList("sample.pdf", "123.pdf", "hello.txt"));

  Set<String> matchedFiles = fileSearch.getMatchedFiles();

  for (String matchedFile : matchedFiles) {
   System.out.println(matchedFile);
  }

 }

}


You may like



No comments:

Post a Comment