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

JGRASP only: B01 - Searching a File You will write a program that will look for

ID: 3913036 • Letter: J

Question

JGRASP only:
B01 - Searching a File You will write a program that will look for a file with a given name in a specified directory structure. Your program needs to: Ask the user for the path of the directory to recursively look for the file. Ask the user for the name of the file to look for. Define a recursive method searchFile that will receive the path of the current directory to look for the file, and the name of the file given by the user. Your program will check the name of the files in the current directory to see if any of them have a filename we are looking for. If so, your program will print the path to that file. Then, iterate through the subdirectories in the current directory and call the recursive method searchFile with those subdirectories and the same file we are looking for. Hint: Define the following method. public static void searchFile(String path, String filename) NOTE: A similar but different example can be found in Listing 18.7.

Explanation / Answer

public void searchFile(String path, String filename){

    try {

         File directory = new File(path);
         File[] fList = directory.listFiles();
         if (flist.length == 0)
            return;
         else {
            for (int i = 0; i<flist.length; i++){
                if (flist[i].isFile()){
                   if (flist[i].getName().equals(filename))
                      System.out.println(path + "/" + filename)
                }
                else {
                   if (flist[i].isDirectory()){
                      String path1 = path + "/" + flist[i].getName();
                      searchFile(path1, filename);
                   }
                }
            }
         }
        
           
    }
    catch(Exception e){
       e.printStackTrace();
    }
}