Reputation: 17
What is the best way to iterate on filed in a specific folder, but without loops? i.e, the for loop will end when all the files be checked once.
My example code (with loop):
File dir = new File(svnClient.getDestinationPath().getAbsolutePath());
for (File child : dir.listFiles())
{
report.report("File name: " + child.getName());
}
Upvotes: 0
Views: 280
Reputation: 34014
Abuse the listFiles(FileFilter filter)
method, put your logic in the callback and ignore the return value.
File dir = ...
dir.listFiles(new FileFilter() {
boolean accept(File child) {
report.report("File name: " + child.getName());
return false;
}
});
Upvotes: 0
Reputation: 32949
Recursion:
public void myMethod(){
File dir = ...;
List<File> files = Arrays.asList(dir.listFiles());
recurse(files.iterator());
}
private void recurse(Iterator<File> iterator){
if (iterator.hasNext()){
File file = iterator.next();
report.report(file.getName());
recurse(iterator);
}
}
Upvotes: 3