Upload Quiz12.java with solution to the following Write a public static method f
ID: 3915339 • Letter: U
Question
Upload Quiz12.java with solution to the following Write a public static method fileCount that accepts a String representing a path on your computer as a parameter and returns the number of files in that path, including files in sub-folders, and sub-folders of sub-folders, etc... to all depths within. Example use shown below: String root -"C: Users HomeDocuments BCT ISummer 2018"; //String root-"C:V"; // this takes WAY too long to finish System.out.printlnC"Number of files+ Quiz12.fileCount(root)); // 1789 files counted Since we now have experience with File objects, arrays, and the for-each loop, the following starter code could be of tremendous help here public static void main(String[] args) throws FileNotFoundException { //String root "C:I"; int fileCount 0; int folderCount 0; // C: drive is way too huge, program runs forever, so try sub-folder: String root-"C: Users Home Documents BC ISummer 2018"; File start new File(root); File[] arrayOfFiles start.listFilesO; for (File found : array0fFiles) if (found.isFileO) fileCount++ else t folderCount++; System.out.printlnC"Number of filesfileCount); System.out.println("Number of folders"folderCount); //this counts 5 files and 18 folders, which is not correct // it never counts files in sub-folders of sub-folders of sub-folders... Above gives me both the file and folder count from the path at String root, using the existing Oracle methods of boolean .isFile) and .listFiles() to get a folder content as an array of File]. Problem is, it never goes into the files and folders of the sub-foldersExplanation / Answer
public class FileUse {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = new String("C:\Users\USER\Desktop\test");
System.out.println(fileCount(str));
}
public static int fileCount(String root){
File start = new File(root);
if(start.list().length==0){
return 0;
}
int count = 0;
File[] arrayOfFiles = start.listFiles();
for(File found: arrayOfFiles){
if(found.isFile()){
count++;
}
else{
String folderRoot = found.getPath();
count+=fileCount(folderRoot);
}
}
return count;
}
}
//I hope u got the code, There is the required functions fileCount with main and tested with an example
// It works fine. All the Best. For any doubt comment.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.