Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a function “find_file” that accepts a full directory path parameter (i.e.

ID: 3841601 • Letter: C

Question

Create a function “find_file” that accepts a full directory path parameter (i.e., C:Userscs401DesktopDocs) and a file name parameter (i.e., MyFile.txt) that recursively searches all folders and subfolders under the provided path for the specified filename. When found, the full file pathname should be printed. Note there may be multiple files within a folder structure that match the specified name. If the file is not found, nothing should be printed. If listing the files in a folder results in a PermissionError – skip that folder.

Sample output:

find_file("C:\Users\cs401\Desktop\Docs", "build.xml")

C:UserssdDesktopDocsArtArraysuild.xml

C:UserssdDesktopDocscommClientuild.xml

C:UserssdDesktopDocshola105uild.xml

Explanation / Answer

package chegg;

import java.io.File;
import java.util.Scanner;

public class FileFinder {

   public static void main(String[] args) {
       System.out.println("Enter the path:");
      
       Scanner sc=new Scanner(System.in);
       String currentPath=sc.next();
       System.out.println("ENter the filename:");
       String fileName=sc.next();
      
       StringBuffer sb=new StringBuffer();
       for(char c:currentPath.toCharArray()){
           if(c=='\') // \ is the escape sequence for ;
               sb.append("\\");
           else
               sb.append(c);
       }
      
       String absolutePath = searchForFile(currentPath,fileName);
       System.out.println(absolutePath);
   }

   public static String searchForFile(String currentPath, String fileName) {
       String path="";
      
       File file=new File(currentPath);
       //System.out.println("fcall"+(file.isFile()?"File":"dir")+file.getAbsolutePath());
       if(!path.equals(""))
           return path;
       else if(file.getName().equals(fileName)){
           path=file.getAbsolutePath();
           System.out.println(file.getName());
       }
       else if(file.isDirectory()){
           File files[]=file.listFiles();
           for(File f:files){
               // windows have some hidden files which are used for drive management
               //for some files, the process might not have permission.
               //when we try to access such folders,we might get NullPointerException
               if(!f.isHidden()){
                   path=searchForFile(file.getAbsolutePath()+"\"+f.getName(),fileName);
                   if(!path.equals(""))
                       break;
               }
           }
          
       }
      
       return path;
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote