Authors Top

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this tutorial, we’ll see a few different solutions to find if a given file or directory exists using Scala.

2. Using Java IO

Since Scala can use any java library, the first possibility is using the Java standard IO module.

To test if a file or directory exists, we can use the File#exists() method. This method returns a boolean indicating if the file or directory denoted by the given pathname exists:

scala> import java.io.File

scala> File("/tmp/baeldung.txt").exists()
val res0: Boolean = true

scala> File("/tmp/unexisting_file").exists()
val res1: Boolean = false

scala> File("/tmp").exists()
val res2: Boolean = true

3. Using Java NIO

Since Java 7 we have another solution to test if a given file exists, using Files.exists(filename) method:

scala> import java.nio.file.Files

scala> import java.nio.file.Paths

scala> Paths.get("/tmp/baeldung.txt")
val res0: java.nio.file.Path = /tmp/baeldung.txt

scala> Files.exists(Paths.get("/tmp/baeldung.txt"))
val res1: Boolean = true

scala> Files.exists(Paths.get("/tmp/unexisting_file"))
val res2: Boolean = false

scala> Files.exists(Paths.get("/tmp"))
val res3: Boolean = true

Just like the previous example, this method also returns a boolean indicating if the file or directory denoted by the given pathname exists.

4. Conclusion

In this article, we saw how we can check if a given file exists by leveraging the Scala and Java interoperability capabilities.

Authors Bottom

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!