JAVA. B01 - Searching a File You will write a program that will look for a file
ID: 3915002 • Letter: J
Question
JAVA.
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
import java.io.File; import java.util.Scanner; public class FileSearch { public static void searchFile(String path, String filename) { File[] files = new File(path).listFiles(); int index; String name; for (File file : files) { if (file.isFile()) { index = file.getName().indexOf('.'); if(index != -1) { name = file.getName().substring(0, index); if (name.equals(filename)) { System.out.println(file.getAbsolutePath()); } } } else if (file.isDirectory()) { searchFile(file.getAbsolutePath(), filename); } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter path of the directory: "); String path = in.nextLine(); System.out.print("Enter file name: "); String filename = in.nextLine(); searchFile(path, filename); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.