3

I have this function below for filter a list of files. I was wondering how I could filter so it only returns files that end in .png or .txt?

 def getListOfFiles(directoryName: String): Array[String] = {
 return (new File(directoryName)).listFiles.filter(_.isFile).map(_.getAbsolutePath)
} 

Thanks for the help, guys.

3 Answers3

5

Just add a condition to filter:

(new File(directoryName)).listFiles.
  filter { f => f.isFile && (f.getName.endsWith(".png") || f.getName.endsWith(".txt")) }.
  map(_.getAbsolutePath)

or use listFiles(FileFilter) instead of just listFiles, but it's less convenient (unless you use experimental Scala single method interface implementation)

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • The SAM version would be something like `new File(directoryName).listFiles(file => file.isFile && file.getName.endsWith(".png") || file.getName.endsWith(".png"))` – phw Nov 20 '18 at 16:21
0

Just like you would filter ordinary strings:

val filenames = List("batman.png", "shakespeare.txt", "superman.mov")
filenames.filter(name => name.endsWith(".png") || name.endsWith(".txt"))
// res1: List[String] = List(batman.png, shakespeare.txt)
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
0

Alternative approach, a bit less verbose

import scala.reflect.io.Directory
Directory(directoryName).walkFilter(_.extension=="png")

It returns an Iterator[Path] which can be converted with.toArray[String]

Pierre Gramme
  • 1,209
  • 7
  • 23