placplacboom placplacboom - 5 months ago 20
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 _ =>


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.