0

Good Morning in my timezone.

I have the following code:

Iterator<File> files = FileUtils.iterateFiles(new File(directoryPath), new String[]{"java"}, true);

        for(String file : ws){
            while(files.hasNext()){
                current = files.next();
                if(!current.isDirectory()){
                    if(current.getName().matches(file+".*ServiceProxy.*")){
        //I need to start the cycle again from the beginning to search in each
    //file for the ServiceProxy string
    //Something like this
            // cloneFiles = files.clone();
         //while(cloneFiles.hasNext()){
              file = files.next();
              //search inside the file code
         }
                    }
                }
            }   
        }

I want to clone the Iterator because this action is very expensive in terms of time

FileUtils.iterateFiles(new File(directoryPath), new String[]{"java"}, true);

Thanks in advance Best regards

tt0686
  • 1,771
  • 6
  • 31
  • 60

2 Answers2

0

You can use Iterable:

Iterable<File> filesIterable = new Iterable<>(){
    public Iterator<File> iterator() {
        return FileUtils.iterateFiles(...);
    }
};

...

for (File file : filesIterable) {
    ...
}

// ... and you may reuse it over and over. 
// For each cycle declaration there will be a new `Iterator` created.

for (File file : filesIterable) {
    ...
}

It works like this:

  1. for-each loop asks filesIterable to create a new Iterator
  2. filesIterable calls iterator()
  3. FileUtils.iterateFiles creates a new Iterator
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • But if i use the filesIterable object do not the FilesUtils.iterateFiles will be change either ? Do not the filesIterable object uses the reference for the FilesUtils.iterateFiles object ? Thanks for the quick answer – tt0686 Oct 25 '13 at 09:43
  • The problem with that aproach is that it is always calling in my case the FileUtils.iterateFiles(new File(directoryPath), new String[]{"java"}, true); , and that is what i want to avoid because is a very expensive operation, that is why i want to clone the Iterator that this function returns Thanks for the answer i your time – tt0686 Oct 25 '13 at 10:00
  • Ah, yeah, you're right I've recalled this weirdness in `FileUtils`. – Andrey Chaschev Oct 25 '13 at 10:01
0

You can use

Collection<File> files = FileUtils.listFiles(new File(directoryPath), 
    new String[]{"java"}, true);

to create a collection of files and then reuse it for further iterating. This way it won't scan your root folder each time you want to iterate over files.

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68