
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: May 6, 2023
In this tutorial, we’ll see a few different solutions to find if a given file or directory exists using Scala.
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
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.
In this article, we saw how we can check if a given file exists by leveraging the Scala and Java interoperability capabilities.