Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala find files that match a wildcard String

How to obtain an Array[io.BufferedSource] to all files that match a wildcard in a given directory ?

Namely, how to define a method io.Source.fromDir such that

val txtFiles: Array[io.BufferedSource] = io.Source.fromDir("myDir/*.txt") // ???

Noticed FileUtils in Apache Commons IO, yet much preferred is a Scala API based approach without external dependencies.

like image 657
elm Avatar asked Dec 18 '14 10:12

elm


1 Answers

Here is an answer based on this great answer from @som-snytt:

scala> import reflect.io._, Path._
import reflect.io._
import Path._

scala> "/temp".toDirectory.files.map(_.path).filter(name => name matches """.*\.xlsx""")
res2: Iterator[String] = non-empty iterator

as an Array:

scala> "/temp".toDirectory.files.map(_.path).filter(name => name matches """.*\.xlsx""").toArray
res3: Array[String] = Array(/temp/1.xlsx, /temp/2.xlsx, /temp/3.xlsx, /temp/a.1.xlsx, /temp/Book1.xlsx, /temp/new.xlsx)
like image 175
MaxU - stop WAR against UA Avatar answered Sep 20 '22 12:09

MaxU - stop WAR against UA