1. Overview

In this tutorial, we will see how we can list files from a local filesystem in Scala.

2. List Files in a Directory in Scala

Scala doesn’t provide a built-in directive to access the local filesystem, but it uses its Java interoperability to allow access to it. While the java.nio.file API is not very idiomatic for Scala code, it can be improved by making use of the scala.collection.JavaConverters helpers.

2.1. List Local Files

Let’s start by listing the files in our local filesystem. Let’s assume the following directory under /tmp/baeldung/ :

$ tree /tmp/baeldung/
├── a.txt
├── another_dir
│   └── c.txt
└── b.json

1 directory, 3 files

And now let’s read it in our Scala script:

scala> import java.nio.file.{FileSystems, Files}

scala> import scala.collection.JavaConverters._

scala> val dir = FileSystems.getDefault.getPath("/tmp/baeldung")
val dir: java.nio.file.Path = /tmp/baeldung

scala> Files.list(dir).iterator().asScala.foreach(println)

We can see from the above that we obtained a list of both files and the directory as well.

We can easily list just regular files instead of directories as well by filtering the stream with the Files.isRegularFile() method:

scala> Files.list(dir).iterator().asScala.filter(Files.isRegularFile(_)).foreach(println)

And now we only list regular files.

2.2. List Files Recursively

When we have nested directories and files, we may need to list them all as well. In our specific case, we may want to include the c.txt file too.

If we use the Files.walk() method instead of Files.list() we used before, we’ll list all nested files out of the box:

scala> Files.walk(dir).iterator().asScala.filter(Files.isRegularFile(_)).foreach(println)

Once again, we filter our directories, but we could remove the filter to show directories as well:

scala> Files.walk(dir).iterator().asScala.foreach(println)

2.3. Filter Listed Files by Extension

A very common practice is to filter the listed files by extension, e.g., filtering JSON files. The simplest way is to check the end part of the file name:

scala> Files.list(dir).iterator().asScala.filter(_.getFileName.toString().endsWith(".json")).foreach(println)

3. Conclusion

In this article, we saw how to list files from the local filesystem using Scala and its Java interoperability features.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.