By Alvin Alexander. Last updated: August 15, 2018
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.