Recursively Searching Files and Directories Summary Build a class and a driver f
ID: 3794677 • Letter: R
Question
Recursively Searching Files and Directories
Summary
Build a class and a driver for use in searching your computer’s secondary storage (hard disk or flash memory) for a specific file from a set of files indicated by a starting path. Lets start by looking at a directory listing. Note that every element is either a file or a directory.
Introduction and Driver
In this assignment, your job is to write a class that searches through a file hierarchy (a tree) for a specified file. Your FindFile class will search a directory (and all subdirectories) for a target file name.
For example, in the file hierarchy pictured above, the file “lesson.css” will be found once in a directory near the root or top-level drive name (e.g. “C:”) . Your FindFile class will start at the path indicated and will search each directory and subdirectory looking for a file match. Consider the following code that could help you build your Driver.java:
String targetFile = “lesson.css”;
String pathToSearch =”
C:\WCWC”; FindFile finder = new FindFile(MAX_NUMBER_OF_FILES_TO_FIND);
Finder.directorySearch(targetFile, pathToSearch);
File Searching
In general, searching can take multiple forms depending on the structure and order of the set to search. If we can make promises about the data (this data is sorted, or deltas vary by no more than 10, etc.), then we can leverage those constraints to perform a more efficient search. Files in a file system are exposed to clients of the operating system and can be organized by filename, file creation date, size, and a number of other properties. We’ll just be interested in the file names here, and we’ll want perform a brute force (i.e., sequential) search of these files looking for a specific file. The way in which we’ll get file information from the operating system will involve no ordering; as a result, a linear search is the best we can do. We’d like to search for a target file given a specified path and return the location of the file, if found. You should sketch out this logic linearly before attempting to tackle it recursively.
FindFile Class Interface
FindFile(int maxFiles): This constructor accepts the maximum number of files to find.
void directorySearch(String target, String dirName): The parameters are the target file name to look for and the directory to start in.
int getCount(): This accessor returns the number of matching files found
String[] getFiles(): This getter returns the array of file locations, up to maxFiles in size.
Requirements
Your program should be recursive.
You should build and submit at least two files: FindFile.java and Driver.java.
Throw an exception (IllegalArgumentException) if the path passed in as the starting directory is not a valid directory.
Throw an exception if you've found the MAX_NUMBER_OF_FILES_TO_FIND and catch and handle this in your main driver. Your program shouldn't crash but rather exit gracefully in the unusual situation that we've discovered the maximum number of files we were interested in, reporting each of the paths where the target files were found.
The only structures you can use in this assignment are basic arrays and your Stack, Queue, or ArrayList from the previous homeworks. Do not use built-in data structures like Java's ArrayList. To accomplish this, put in the following constructor and method to your ArrayList, Stack, or Queue:
public ArrayList(Object[] input) { data = input;
numElements = input.length;
}
public Object get(int index) {
return data[index];
}
Explanation / Answer
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class FindFiles {
public static void main(String[] args) {
try {
Scanner console = new Scanner(System.in);
System.out.print("Enter name of directory to start search: ");
String directory = console.nextLine();
System.out.print("Enter filename extension to search for: ");
String extension = console.nextLine();
ArrayList<String> foundFiles = new ArrayList();
DirectorySearcher ds = new DirectorySearcher(extension);
File dir = new File(directory);
ds.findMatchingFiles(dir);
foundFiles = ds.getFoundFiles();
System.out.println("Found these files under directory " + directory
+ ":");
for (String f : foundFiles) {
System.out.println(f);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
import java.io.File;
import java.util.ArrayList;
/**
* Find the files in the given directory and subdirectories that end with the
* specified extension.
*
* @author your name
*
*/
public class DirectorySearcher {
private String extension;
private ArrayList<String> foundFiles;
/**
* Build a DirectorySearcher object to find matches with the given
* extension.
*
* @param ext
* Filename extension to match, such as ".java"
* @param results
* ArrayList to hold found files
*/
public DirectorySearcher(String ext) {
extension = ext;
foundFiles = new ArrayList<String>();
}
/**
* Recursively add files with matching extension to the list of files. If
* the file is a directory, recursively call the method to add files from
* the subdirectory to the list.
*
* @param f
* File to check: if a file, check its name; if a directory,
* check its files
* @return
*/
public void findMatchingFiles(File f) {
// Use the pseudocode outlined in the homework
// to help solve this recursive method.
// Loop through directory, to find all files and sub-directories.
try {
for (File fileEntry : f.listFiles()) {
// Add the file entry to this result.
// If the file entry is a sub-directory, search it recursively.
if (fileEntry.isDirectory()) {
findMatchingFiles(fileEntry);
} else {
if (fileEntry.getName().contains(extension))
this.foundFiles.add(fileEntry.getName());
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* @return the foundFiles
*/
public ArrayList getFoundFiles() {
return foundFiles;
}
}
OUTPUT:
Enter name of directory to start search: D:CAndCppTCPP
Enter filename extension to search for: .txt
Found these files under directory D:CAndCppTCPP:
input.txt
output.txt
fun.txt
colmnsdata.txt
inputfile.txt
outputfile.txt
file.txt
text.txt
Order.txt
HW 1 - Random Numbers.txt
inputfile.txt
output.txt
inputfile.txt
sample.txt
results.txt
temprature.txt
dict.txt
file.txt
input.txt
output.txt
BoysNamesCanada2015.txt
GirlsNamesCanada2015.txt
BoysNamesCanada2015.txt
GirlsNamesCanada2015.txt
input.txt.txt
input.txt.txt
textfile.txt
textfile.txt
file.txt
myData.txt
AnswerOut.txt
numInput.txt
studentdata.txt
studentoutdata.txt
lastwords.txt
words.txt
dict.txt
plain.txt
output.txt
input.txt
MortgageTablePgmV2_Results.txt
data.txt
TemperatureData.txt.txt
TemperatureData.txt.txt
data.txt
Lab9_1data.txt
numbers.txt
reverse.txt
SummaryOfSale_yourLastName.txt
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.