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

Create a program that will search through all the files in a directory and throu

ID: 3567172 • Letter: C

Question

Create a program that will search through all the files in a directory and through all files in subdirectories recursively. The program will search each file for a given string and will report the number of lines that contain that string. Command line parameters will be used to specify the directory and the string.

So, for example, if the command line parameters are
mysteries Holmes
then the program would search recursively through the directory mysteries and all its subdirectories counting the number of lines in all files that contain the string Holmes.

Note that the string being used as the search key may be part of a larger word. For example, if the key were ear, then it would be found in the previous lines as part of the larger word search.

If a string appears multiple times on a line, that line is only counted once.

You should have a recursive method in the program that returns the count.1 It

Explanation / Answer

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Scanner;

public class DirectorySearch {

public static int count = 0;

public static void main(String[] args) throws IOException {

countLinesWithString("mysteries", "Holmes");

System.out.println("Holmes :"+ count);

count=0;

countLinesWithString("mysteries", "watson");

System.out.println("watson :"+ count);

count=0;

countLinesWithString("mysteries", "Watson");

System.out.println("Watson :"+ count);

count=0;

countLinesWithString("mysteries", "Moriarty");

System.out.println("Moriarty :"+ count);

}

public static void countLinesWithString(String directoryName,String key) {

File directory = new File(directoryName);

File[] fList = directory.listFiles();

for (File file : fList) {

if (file.isFile()) {

try {

Scanner scan;

scan = new Scanner(file);

while (scan.hasNextLine()) {

if(scan.nextLine().contains(key))

count++;

}

scan.close();

} catch (FileNotFoundException e) {

System.out.println("Error !!");

}

} else if (file.isDirectory()) {

countLinesWithString(file.getAbsolutePath(), key);

}

}

}

}

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