i know the basics of recursion but in the given code i m facing difficulty to understand the flow.
please help me guys…
public ArrayList<String> searchFolders(File fo) {
if (fo.isDirectory()) {
String internalNames[] = fo.list();
for (int i = 0; i < internalNames.length; i++) {
searchFolders(new File(fo.getAbsolutePath() + "\\"+ internalNames[i]));
path = fo.getAbsolutePath() + "\\" + internalNames[i];
}
}
if (fo.isFile()) {
alist.add(fo.toString());
}
return alist;
}
Basically, this code is getting all of the contents of a directory and adding them to the global variable
alist.You give it a directory.
If it’s a file, then it adds its name to the list and the method returns (files can’t have subfolders).
If it’s a folder, then it lists all of the things in the folder:
And then executes the same search for each item in the folder:
searchFolders(new File(fo.getAbsolutePath() + "\\"+ internalNames[i]));So, if the item that you are currently searching is a file (if
fo.getAbsolutePath() + "\\"+ internalNames[i]is the directory of a file), then it just adds the file to the global ArrayList.Otherwise, if it is a folder, it searches it just like it just searched the folder that it just looks at, and lists all of the files in the folder.
You don’t seem to use the variable
path.When you return
alist, you are returning all of the files that you have found in the folder (and its subfolders) so far.You are not returning folder names, since when
fo.isDirectory(), you aren’t adding its name toalist.