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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21177107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:00:00  来源:igfitidea点击:

How to check if path or file exist in Scala

scala

提问by Low Kian Seong

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

如何检查 Scala 中是否存在类似于 Python 的路径/文件?下面是一个例子:

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

采纳答案by Low Kian Seong

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

好吧,对不起,我找到了我自己问题的答案:

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

回答by Vladimir Matveev

Since Java 7 the better way would be

从 Java 7 开始,更好的方法是

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

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

回答by Carlos Caldas

It is an old question, but I still need it needs some update. You should use isFileor isRegularFileinstead of existssince existsdon′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.

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

Using java.io

使用 java.io

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

Using java.nio

使用 java.nio

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

回答by markus

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

works as well.

也有效。