Reputation: 597
I am trying to make a search method that it takes a path, search through its folders and directories, and print out the files. Also at the end I want it to print the number of files in over all.
Here is my code:
public static void main(String[] args) {
search("C:\\Program Files (x86)\\Adobe");
}
public static void search(String folderpath){
File directory = new File(folderpath);
int numberOfFiles = 0;
for (File element : directory.listFiles()){
if(element.isDirectory()){
search(element.getAbsolutePath());
}
else{
numberOfFiles++;
System.out.println(element);
}
};
System.out.println(numberOfFiles);
};
The result is like:
folder
1
2
3
folder2
1
folder3
4
5
And it never come up with one final number for numberOfFiles
.
Does anyone know how to stop it to from printing numberOfFiles
for every folder, and just print it once at the end ?
Upvotes: 1
Views: 1230
Reputation: 36401
Your method is recursive which is a good idea, but you can't write something at the end of the recursion by placing it in the method itself (at least this way).
So, here is a possible correction. Make search
a method that calculates how many files there is in (direct files, and file in its subdirs).
public static void main(String[] args) {
System.out.println("# of files "+search("C:\\Program Files (x86)\\Adobe"));
}
public static int search(String folderpath){
File directory = new File(folderpath);
int numberOfFiles = 0;
for (File element : directory.listFiles()){
if (element.isDirectory()) { // count the files for this subdir
numberOfFiles += search(element.getAbsolutePath());
}
else { // one more file
numberOfFiles++;
System.out.println(element);
}
}
// return the number of files for this dir and its sub dirs
return numberOfFiles;
}
Upvotes: 4
Reputation: 85779
You're counting the number of files in the current folder and storing this in a local variable. Since the method is recursive, you will only get the number of files of the current folder being inspected.
Try returning the number of files in the current folder plus the number of files in each subfolder. Then, in the client method, consume the result as needed.
Here's how the code should look like:
public static void main(String[] args) {
String pathToInspect = "C:\\Program Files (x86)\\Adobe"
int numberOfFiles = search(pathToInspect);
System.out.println("Number of files in " + pathToInspect + ": " + numberOfFiles);
}
//changed return type from void to int
public static int search(String folderpath) {
File directory = new File(folderpath);
int numberOfFiles = 0;
for (File element : directory.listFiles()) {
if(element.isDirectory()) {
//add the number of files of subfolder
numberOfFiles += search(element.getAbsolutePath());
} else {
numberOfFiles++;
}
}
//return number of files found
return numberOfFiles;
}
Upvotes: 4