How to check if path or file exist in Scala

Scala

Scala Problem Overview


How do I check if a path / file exists in Scala similar to Python ? An example below:

os.path.exists("/home")
Out[4]: True

Scala Solutions


Solution 1 - Scala

Since Java 7 the better way would be

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

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

Solution 2 - Scala

Well, sorry I found the answer to my own question:

scala> new java.io.File("/tmp").exists
res0: Boolean = true

Solution 3 - Scala

It is an old question, but I still need it needs some update. You should use isFile or isRegularFile instead of exists since exists don´t take in account if is a File or a Directory and can mislead the application in case there is a directory with the same name.

Using java.io

new java.io.File("/tmp/sample.txt").isFile

Using java.nio

java.nio.file.Files.isRegularFile(java.nio.file.Paths.get("/tmp/sample.txt"))

Solution 4 - Scala

scala.reflect.io.File("/tmp/sample.txt").exists

works as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMuhammad Lukman LowView Question on Stackoverflow
Solution 1 - ScalaVladimir MatveevView Answer on Stackoverflow
Solution 2 - ScalaMuhammad Lukman LowView Answer on Stackoverflow
Solution 3 - ScalaCarlos CaldasView Answer on Stackoverflow
Solution 4 - ScalamarkusView Answer on Stackoverflow