Scala: How to list files and directories under a directory

When using Scala, if you ever need to list the subdirectories in a directory, or the files under a directory, I hope this example is helpful:

import java.io.File

object FileTests extends App {

    // list only the folders directly under this directory (does not recurse)
    val folders: Array[File] = (new File("/Users/al"))
        .listFiles
        .filter(_.isDirectory)  //isFile to find files
    folders.foreach(println)

}

If it helps to see it, a longer version of that solution looks like this:

val file = new File("/Users/al")
val files = file.listFiles()
val dirs = files.filter(_.isDirectory)

As noted in the comment, this code only lists the directories under the given directory; it does not recurse into those directories to find more subdirectories. Also as noted, use isFile to check to see if the “files” are files and isDirectory to see if the files are really directories.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.