placplacboom placplacboom - 1 year ago 97
Scala Question

Scala - Get files based on name pattern

I would like to filter the files based on some patterns like :

- Team_*.txt (e.g.: Team_Orlando.txt);
- Name.*.City.txt (e.g.: Name.Robert.California.txt);

Or any name (the pattern * . * - it has spaces because was broken my text).

All the filters come from a database table and they are dynamic.

I'm trying to avoid use commands from SO like cp or mv. Is possible to filter files using patterns like the above ?

Here is what i've tried but got a regex error:

def getFiles(dir:File, filter:String) = {
(dir.isDirectory, dir.exists) match {
case (true, true) =>
dir.listFiles.filter(f => f.getName.matches(filter))
case _ =>

Answer Source

You can use java.nio Files.newDirectoryStream() for that, it will accept pattern in desired format:

val stream = Files.newDirectoryStream(dir, pattern)

Check for detailed description.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download