user4828533
user4828533

Reputation:

Scala filter by extension

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.

Upvotes: 3

Views: 3333

Answers (3)

Pierre Gramme
Pierre Gramme

Reputation: 1254

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]

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170815

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)

Upvotes: 5

om-nom-nom
om-nom-nom

Reputation: 62835

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)

Upvotes: 0

Related Questions