SlideShare a Scribd company logo
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];
}
Solution
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 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 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();
}
/**
* 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

More Related Content

Similar to Recursively Searching Files and DirectoriesSummaryBuild a class .pdf

Files nts
Files ntsFiles nts
Files nts
kalyani66
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
20-packages-jar.ppt
20-packages-jar.ppt20-packages-jar.ppt
20-packages-jar.ppt
bharanidaranramaling
 
Chapter 17
Chapter 17Chapter 17
Find and locate
Find and locateFind and locate
Find and locate
praful borad
 
Impetus White Paper- Handling Data Corruption in Elasticsearch
Impetus White Paper- Handling  Data Corruption  in ElasticsearchImpetus White Paper- Handling  Data Corruption  in Elasticsearch
Impetus White Paper- Handling Data Corruption in Elasticsearch
Impetus Technologies
 
Chapter 2 Linux File System and net.pptx
Chapter 2 Linux File System and net.pptxChapter 2 Linux File System and net.pptx
Chapter 2 Linux File System and net.pptx
alehegn9
 
TagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File SystemsTagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File Systems
Max Völkel
 
TagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File SystemsTagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File Systems
guest52d7e8
 
Asp.net create delete directory folder in c# vb.net
Asp.net   create delete directory folder in c# vb.netAsp.net   create delete directory folder in c# vb.net
Asp.net create delete directory folder in c# vb.net
relekarsushant
 
Java I/O Part 1
Java I/O Part 1Java I/O Part 1
Java I/O Part 1
AshishSingh Bhatia
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
ashishspace
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
Aakash Ugale
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Ch10
Ch10Ch10
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Files
FilesFiles
OS_Ch11
OS_Ch11OS_Ch11
OSCh11
OSCh11OSCh11

Similar to Recursively Searching Files and DirectoriesSummaryBuild a class .pdf (20)

Files nts
Files ntsFiles nts
Files nts
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
20-packages-jar.ppt
20-packages-jar.ppt20-packages-jar.ppt
20-packages-jar.ppt
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Find and locate
Find and locateFind and locate
Find and locate
 
Impetus White Paper- Handling Data Corruption in Elasticsearch
Impetus White Paper- Handling  Data Corruption  in ElasticsearchImpetus White Paper- Handling  Data Corruption  in Elasticsearch
Impetus White Paper- Handling Data Corruption in Elasticsearch
 
Chapter 2 Linux File System and net.pptx
Chapter 2 Linux File System and net.pptxChapter 2 Linux File System and net.pptx
Chapter 2 Linux File System and net.pptx
 
TagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File SystemsTagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File Systems
 
TagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File SystemsTagFS — Tag Semantics for Hierarchical File Systems
TagFS — Tag Semantics for Hierarchical File Systems
 
Asp.net create delete directory folder in c# vb.net
Asp.net   create delete directory folder in c# vb.netAsp.net   create delete directory folder in c# vb.net
Asp.net create delete directory folder in c# vb.net
 
Java I/O Part 1
Java I/O Part 1Java I/O Part 1
Java I/O Part 1
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Ch10
Ch10Ch10
Ch10
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Files
FilesFiles
Files
 
OS_Ch11
OS_Ch11OS_Ch11
OS_Ch11
 
OSCh11
OSCh11OSCh11
OSCh11
 

More from mallik3000

Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdfExplain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
mallik3000
 
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdfExercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
mallik3000
 
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdfestion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
mallik3000
 
Discuss the difference between the two levels of moral development. .pdf
Discuss the difference between the two levels of moral development. .pdfDiscuss the difference between the two levels of moral development. .pdf
Discuss the difference between the two levels of moral development. .pdf
mallik3000
 
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdfDiels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
mallik3000
 
Create a Balance Sheet to record the following transactions for Tayl.pdf
Create a Balance Sheet to record the following transactions for Tayl.pdfCreate a Balance Sheet to record the following transactions for Tayl.pdf
Create a Balance Sheet to record the following transactions for Tayl.pdf
mallik3000
 
Compare Plato and Aristotles philosophies of mathematics and relat.pdf
Compare Plato and Aristotles philosophies of mathematics and relat.pdfCompare Plato and Aristotles philosophies of mathematics and relat.pdf
Compare Plato and Aristotles philosophies of mathematics and relat.pdf
mallik3000
 
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdf
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdfChoose one of the evolutions of Critical Incident Technique (CIT) an.pdf
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdf
mallik3000
 
Change the creature in this java program to a different one .pdf
Change the creature in this java program to a different one .pdfChange the creature in this java program to a different one .pdf
Change the creature in this java program to a different one .pdf
mallik3000
 
Canon Corporation had the following static budget at the beginning o.pdf
Canon Corporation had the following static budget at the beginning o.pdfCanon Corporation had the following static budget at the beginning o.pdf
Canon Corporation had the following static budget at the beginning o.pdf
mallik3000
 
Can someone please prove this equation is an identity. Cos^2.pdf
Can someone please prove this equation is an identity. Cos^2.pdfCan someone please prove this equation is an identity. Cos^2.pdf
Can someone please prove this equation is an identity. Cos^2.pdf
mallik3000
 
Write a program that finds the max binary tree height. (This is an ex.pdf
Write a program that finds the max binary tree height. (This is an ex.pdfWrite a program that finds the max binary tree height. (This is an ex.pdf
Write a program that finds the max binary tree height. (This is an ex.pdf
mallik3000
 
What happens when the JVM encounters a wait () callSolution=.pdf
What happens when the JVM encounters a wait () callSolution=.pdfWhat happens when the JVM encounters a wait () callSolution=.pdf
What happens when the JVM encounters a wait () callSolution=.pdf
mallik3000
 
Write a program in c++ that maintains a telephone directory. The Tel.pdf
Write a program in c++ that maintains a telephone directory. The Tel.pdfWrite a program in c++ that maintains a telephone directory. The Tel.pdf
Write a program in c++ that maintains a telephone directory. The Tel.pdf
mallik3000
 
Using the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdfUsing the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdf
mallik3000
 
Why are supplies and inventory not considered plant assetsSolut.pdf
Why are supplies and inventory not considered plant assetsSolut.pdfWhy are supplies and inventory not considered plant assetsSolut.pdf
Why are supplies and inventory not considered plant assetsSolut.pdf
mallik3000
 
What is the major purpose of the Federal Reserve System What is the.pdf
What is the major purpose of the Federal Reserve System What is the.pdfWhat is the major purpose of the Federal Reserve System What is the.pdf
What is the major purpose of the Federal Reserve System What is the.pdf
mallik3000
 
What is the role of culture in leader development What culture fact.pdf
What is the role of culture in leader development What culture fact.pdfWhat is the role of culture in leader development What culture fact.pdf
What is the role of culture in leader development What culture fact.pdf
mallik3000
 
What methods can IT use to make sure its initiatives have the suppor.pdf
What methods can IT use to make sure its initiatives have the suppor.pdfWhat methods can IT use to make sure its initiatives have the suppor.pdf
What methods can IT use to make sure its initiatives have the suppor.pdf
mallik3000
 
What is IT infrastructure, and what are the stages and drivers of IT.pdf
What is IT infrastructure, and what are the stages and drivers of IT.pdfWhat is IT infrastructure, and what are the stages and drivers of IT.pdf
What is IT infrastructure, and what are the stages and drivers of IT.pdf
mallik3000
 

More from mallik3000 (20)

Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdfExplain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
Explain how The Capitol Building (in D.C.) is a reflection of Greco-.pdf
 
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdfExercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
Exercise 14-3GURLEY CORPORATION Comparative Condensed Balance Sh.pdf
 
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdfestion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
estion 5 of 34 Sapling Learning Which is the correct name of the fo.pdf
 
Discuss the difference between the two levels of moral development. .pdf
Discuss the difference between the two levels of moral development. .pdfDiscuss the difference between the two levels of moral development. .pdf
Discuss the difference between the two levels of moral development. .pdf
 
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdfDiels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
Diels-Alder Post-lab questions F17. 1) Why do the methylene protons.pdf
 
Create a Balance Sheet to record the following transactions for Tayl.pdf
Create a Balance Sheet to record the following transactions for Tayl.pdfCreate a Balance Sheet to record the following transactions for Tayl.pdf
Create a Balance Sheet to record the following transactions for Tayl.pdf
 
Compare Plato and Aristotles philosophies of mathematics and relat.pdf
Compare Plato and Aristotles philosophies of mathematics and relat.pdfCompare Plato and Aristotles philosophies of mathematics and relat.pdf
Compare Plato and Aristotles philosophies of mathematics and relat.pdf
 
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdf
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdfChoose one of the evolutions of Critical Incident Technique (CIT) an.pdf
Choose one of the evolutions of Critical Incident Technique (CIT) an.pdf
 
Change the creature in this java program to a different one .pdf
Change the creature in this java program to a different one .pdfChange the creature in this java program to a different one .pdf
Change the creature in this java program to a different one .pdf
 
Canon Corporation had the following static budget at the beginning o.pdf
Canon Corporation had the following static budget at the beginning o.pdfCanon Corporation had the following static budget at the beginning o.pdf
Canon Corporation had the following static budget at the beginning o.pdf
 
Can someone please prove this equation is an identity. Cos^2.pdf
Can someone please prove this equation is an identity. Cos^2.pdfCan someone please prove this equation is an identity. Cos^2.pdf
Can someone please prove this equation is an identity. Cos^2.pdf
 
Write a program that finds the max binary tree height. (This is an ex.pdf
Write a program that finds the max binary tree height. (This is an ex.pdfWrite a program that finds the max binary tree height. (This is an ex.pdf
Write a program that finds the max binary tree height. (This is an ex.pdf
 
What happens when the JVM encounters a wait () callSolution=.pdf
What happens when the JVM encounters a wait () callSolution=.pdfWhat happens when the JVM encounters a wait () callSolution=.pdf
What happens when the JVM encounters a wait () callSolution=.pdf
 
Write a program in c++ that maintains a telephone directory. The Tel.pdf
Write a program in c++ that maintains a telephone directory. The Tel.pdfWrite a program in c++ that maintains a telephone directory. The Tel.pdf
Write a program in c++ that maintains a telephone directory. The Tel.pdf
 
Using the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdfUsing the C++ programming language1. Implement the UnsortedList cl.pdf
Using the C++ programming language1. Implement the UnsortedList cl.pdf
 
Why are supplies and inventory not considered plant assetsSolut.pdf
Why are supplies and inventory not considered plant assetsSolut.pdfWhy are supplies and inventory not considered plant assetsSolut.pdf
Why are supplies and inventory not considered plant assetsSolut.pdf
 
What is the major purpose of the Federal Reserve System What is the.pdf
What is the major purpose of the Federal Reserve System What is the.pdfWhat is the major purpose of the Federal Reserve System What is the.pdf
What is the major purpose of the Federal Reserve System What is the.pdf
 
What is the role of culture in leader development What culture fact.pdf
What is the role of culture in leader development What culture fact.pdfWhat is the role of culture in leader development What culture fact.pdf
What is the role of culture in leader development What culture fact.pdf
 
What methods can IT use to make sure its initiatives have the suppor.pdf
What methods can IT use to make sure its initiatives have the suppor.pdfWhat methods can IT use to make sure its initiatives have the suppor.pdf
What methods can IT use to make sure its initiatives have the suppor.pdf
 
What is IT infrastructure, and what are the stages and drivers of IT.pdf
What is IT infrastructure, and what are the stages and drivers of IT.pdfWhat is IT infrastructure, and what are the stages and drivers of IT.pdf
What is IT infrastructure, and what are the stages and drivers of IT.pdf
 

Recently uploaded

C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 

Recently uploaded (20)

C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 

Recursively Searching Files and DirectoriesSummaryBuild a class .pdf

  • 1. 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
  • 2. 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]; } Solution 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 foundFiles = new ArrayList(); DirectorySearcher ds = new DirectorySearcher(extension); File dir = new File(directory);
  • 3. 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 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;
  • 4. foundFiles = new ArrayList(); } /** * 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() {
  • 5. 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