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

Write a recursive function contains () that takes as parameters the name of a fi

ID: 3676762 • Letter: W

Question

Write a recursive function contains() that takes as parameters the name of a file fname and the pathname of a folder and searches for the file in the folder and any subfolder contained within it, directly or indirectly. The function should return True if the file can be found somewhere in the directory structure beginning at the specified folder and False if the file cannot be found anywhere in the specified directory structure. The capitalization of the file should not make any difference in the search, meaning that files containing the same sequence of characters as the parameter fname should be found even if their capitalization does not match fname. The following illustrates several searches using the test folders and directories listed in the problem above:

Explanation / Answer

import java.io.*; import java.util.*; class ToFindFile { public void contains(String nameoffile,File file) { File[] list = file.listFiles(); if(list!=null)// continue searching till the list becomes null for (File fil : list) { if (fil.isDirectory()) { System,out.println(“ false continue searching by calling the function again using recursion”); contains(nameoffile,fil); } else if (nameoffile.equalsIgnoreCase(fil.getName())) {System.out.println(“true the file has been found “); System.out.println(fil.getParentFile()); } } } public static void main(String[] args) { TOFindFile find = new FindFile(); Scanner scan = new Scanner(System.in); System.out.println("Enter the file to be searched.. " ); String nameoffile = scan.next(); System.out.println("Enter the directory where to search "); String directory = scan.next(); find.contains(nameoffile,new File(directory)); } }

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