如何检查路径或文件在 Scala 中是否存在

如何检查 Scala 中是否存在类似 Python 的路径/文件:

os.path.exists("/home")
Out[4]: True
67990 次浏览

很抱歉我找到了自己问题的答案:

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

因为 Java7更好的方法是

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


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

这是一个老问题,但我仍然需要一些更新。您应该使用 isFileisRegularFile而不是 exists,因为 exists不考虑是文件还是目录,如果有同名目录,可能会误导应用程序。

使用 java.io

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

使用 java.nio

java.nio.file.Files.isRegularFile(java.nio.file.Paths.get("/tmp/sample.txt"))
scala.reflect.io.File("/tmp/sample.txt").exists

效果也不错。