placplacboom placplacboom - 2 months ago 8
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 _ =>
Array[File]()
}
}

Answer

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

val stream = Files.newDirectoryStream(dir, pattern)

Check http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob for detailed description.