File and Folder search through Java Code

 


Recently we can see most of the first round interview for experienced candidate will be written or programming test. One of the simple and easy programming question asked in interview is to search files and Folder from the given drive using java code.

Question:
Need to search File or Folder or both from the given root directory. 
Input parameters are File/Folder/Both and file to search and root directly.
Program should be run from command prompt. 
Need to use Java regular expression to match file or folder names.

By based on above conditions candidate need to write the code within an hour. In tutorial we will see a sample program for the above question.


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;

public class FileFolderSearch {
 
 private List<String> searchResult = new ArrayList<String>();
 private Pattern pattern;  
 private Matcher matcher; 

 public static void main(String[] args) {
  
  if(args.length < 3){
   System.err.println("Insufficient input. Please input search type and root folder");
   System.err.println("Example : FileFolderSearch <file/folder/both> <D:\\> <^*file*.j*> ");
   System.exit(0);
  }
  if(!(args[0].equalsIgnoreCase("file") || args[0].equalsIgnoreCase("folder") || args[0].equalsIgnoreCase("both"))){
   System.err.println("Invalid search type. Please enter file/folder/both");
   System.exit(0);
  }  
  File rFolder = new File(args[1]);
  if((!rFolder.isDirectory())){
   System.err.println("Invalid root folder or Folder not exisit !!!");
   System.exit(0);
  }
   
  String sType = args[0];
  String fileName = args[2];
  FileFolderSearch obj = new FileFolderSearch();
  obj.searchMyItems(rFolder, fileName, sType);
  obj.printSearchResult();
  
 }
 
 /**
  * Method to search files and folder from root directory 
  * @param target
  * @param fileName
  * @param sType
  */
 public void searchMyItems(File target, String fileName, String sType)     
    {     
        if(target != null && target.isDirectory()) {     
            File[] files = target.listFiles();  
            if (files != null) {  
                for(File file:files) {     
                        pattern = Pattern.compile(fileName);     
                        matcher = pattern.matcher(file.getName());     
                        if(matcher.find()){
                         if(sType.equalsIgnoreCase("both")){
                                searchResult.add(file.getAbsoluteFile().toString());
                         }else if(sType.equalsIgnoreCase("file") && (file.isFile()) ){
                          searchResult.add(file.getAbsoluteFile().toString());
                         }else if(sType.equalsIgnoreCase("folder") && (file.isDirectory()) ){
                          searchResult.add(file.getAbsoluteFile().toString());
                         }
                        }
                    if(file.isDirectory()){     
                     searchMyItems(file, fileName, sType);
                    }
                }     
            }  
        }     
    }    
 
 
 /**
  * Method used to search file/folder from the given root folder
  * @param sType
  * @param rFolder
  * @return
  */ 
 public void searchMyItems(String sType, File rFolder){
  try{
   File[] ff = rFolder.listFiles();
    for(int i=0;i<ff.length;i++){
     if(sType.equalsIgnoreCase("both") )
     if(new File(ff[i].getName()).isDirectory()){
      searchMyItems(sType, new File(ff[i].getName()));
     }
     System.out.println(ff[i].getName());  
    }
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * Method used to print all search result items
  * @param searchResult
  */
 public void printSearchResult(){
  
  // check for no. of search items stored in list.
  if(searchResult.size() == 0){
   System.out.println("Oops, NOT FOUND !!!");
   return;
  }
  
  // Print all search items
  for (Iterator<String> iterator = searchResult.iterator(); iterator.hasNext();) {
   String string = (String) iterator.next();
   System.out.println(string);
  }
  
  System.out.println("Total no. of items found : "+searchResult.size());
 }
}


OUTPUT:


File and Folder search through Java Code





No comments:
Write comments