« Return to Thread: Request for eachFileRecursive

Re: Request for eachFileRecursive

by Andrew O'Malley :: Rate this Message:

Reply to Author | View in Thread

Hi all,

FYI, below is the implementation I use. You are free use it or discard  
it as you see fit.

I named it listRecursively to match the deleteRecursively method  
already in FileExtras.

However, that's pretty verbose for a commonly used function. How about  
recurse?

And I agree completely with Stepan that an Iterable approach is  
better. You can then use it in for comprehensions such as:

for (file <- "/Users/andrew".toFile.recurse if file.getName == ".svn") {
        ...
}

Cheers,
Andrew

   def listRecursively() = new Iterator[File] {
     // Seperate files and dirs so that files can be processed first  
to minimise the queue size
     val files = new Queue[File]();
     val dirs = new Queue[File]();
     enqueue(file)

     def enqueue(dir: File) = {
       for (file <- dir.listFiles()) if (file.isDirectory())  
dirs.enqueue(file) else files.enqueue(file)
       dir
     }

     def hasNext = files.length != 0 || dirs.length != 0

     def next() = {
       if (!hasNext) throw new NoSuchElementException("EOF")
       if (files.length != 0) files.dequeue else enqueue(dirs.dequeue)
     }
   }


On 25/07/2008, at 1:40 AM, Jesse Eichar wrote:

> I like that.  That would allow me to do my usual case but also the  
> other operations I was thinking about like find, filter, etc...
>
> Cool.  I will get on this.
>
> On 24-Jul-08, at 4:55 PM, Stepan Koltsov wrote:
>
>> I think it would be better to have
>>
>> def childrenRecursively: Iterable[File]
>>
>> method, that returns all children recursively, but lazily, i. e. it
>> does evaluation when it elements accessed.
>>
>> S.

 « Return to Thread: Request for eachFileRecursive