In: Computer Science
In this assignment, you will create a Java program to search recursively for a file in a directory.
• The program must take two command line parameters. First parameter is the folder to search for. The second parameter is the filename to look for, which may only be a partial name.
• If incorrect number of parameters are given, your program should print an error message and show the correct format.
• Your program must search recursively in the given directory for the files whose name contains the given filename. Once a match is found, your program should print the full path of the file, followed by a newline.
• You can implement everything in the main class. You need define a recursive method such as: public static search(File sourceFolder, String filename) For each folder in sourceFolder, you recursively call the method to search.
• A sample run of the program may look like this: //The following command line example searches any file with “Assignment” in its name
%java Assign7.Assignment6
C:\CIS 265 Assignment
C:\CIS 265\AS 2\Assignment2.class C:\CIS 265\AS 2\Assignment2.java C:\CIS 265\AS 3\CIS265\Assignment3.class C:\CIS 265\AS 3\CIS265\Assignment3.java C:\CIS 265\AS 4\Assignment4.gpj
Hi please tell me what to input exactly, thanks
You only need to input the source folder where you need to search for the filename and the filename which you need to search. You need to take arguments from command line. i will write the main function for you
public class Demo{
public static search(File sourceFolder, String filename) {
if(sourceFolder.isDirectory()){
File[] arr=sourceFolder.listFiles();//list of all files in dir
for(int i=0;i<arr.length;i++){
search(arr[i],filename);//recursively searches in child dirs
}
}
else if(sourceFolder.isFile()){
if((sourceFolder.getName()).contains(filename)){//checks if filename is substring
System.out.println(sourceFolder.getPath());//prints path of file
}
return;
}
}
public static void main(String []args){
if(args.length!=2){
System.out.println("Please enter 2 arguments, 1st containing the name of the folder and the 2nd containg the filename you want to search for");
System.exit(0);
}
String folder=args[0]; // gets path of dir given
String filename=args[1];// gets filename from user.
File sourceFolder = new File(folder);
search(sourceFOlder,filename);
}
}