12.8. Listing Files in a Directory

Problem

You want to get a list of files that are in a directory, potentially limiting the list of files with a filtering algorithm.

Solution

Scala doesn’t offer any different methods for working with directories, so use the listFiles method of the Java File class. For instance, this method creates a list of all files in a directory:

def getListOfFiles(dir: String):List[File] = {
  val d = new File(dir)
  if (d.exists && d.isDirectory) {
    d.listFiles.filter(_.isFile).toList
  } else {
    List[File]()
  }
}

The REPL demonstrates how you can use this method:

scala> import java.io.File
import java.io.File

scala> val files = getListOfFiles("/tmp")
files: List[java.io.File] = List(/tmp/foo.log, /tmp/Files.scala.swp)

Note that if you’re sure that the file you’re given is a directory and it exists, you can shorten this method to just the following code:

def getListOfFiles(dir: File):List[File] =
  dir.listFiles.filter(_.isFile).toList

Discussion

If you want to limit the list of files that are returned based on their filename extension, in Java, you’d implement a FileFilter with an accept method to filter the filenames that are returned. In Scala, you can write the equivalent code without requiring a FileFilter. Assuming that the File you’re given represents a directory that is known to exist, the following method shows how to filter a set of files based on the filename extensions that should be returned:

import java.io.File

def getListOfFiles(dir: File, extensions: List[String ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.