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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With