Stas Sl
Stas Sl

Reputation: 17

Iterate over files in certain directory without loops in Java

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

Answers (2)

Jörn Horstmann
Jörn Horstmann

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

John B
John B

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

Related Questions