Saving list of items from directory into collection

Viewed 35

I need help with saving list of files into collection.

def collection = {
new File("/path/to/directory/").listFiles().sort { it.name }.reverse().each { def f ->
    println f.name
 }
}

This one is only printing result I want to have in collection

result that i want: list = [file1.jpg, file2.jpg, file3.jpg]

On the internet I found only recursive methods, but those dont fit to my code.

1 Answers

You may define the closure this way

def collection = {
new File("/path/to/directory/").listFiles().sort { it.name }.reverse().collect { f -> f.name
 }
}

and call it to fill the collection

def lst = collection.call()

Alternatively you may directly populat ethe collection with

lst =   new File("/path/to/directory/").listFiles().sort { it.name }.reverse().collect { f -> f.name }
Related