How to check if path or file exist in Scala

前端 未结 4 1012
北荒
北荒 2020-12-05 22:47

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

os.path.exists(\"/home\")
Out[4]: True
相关标签:
4条回答
  • 2020-12-05 22:55
    scala.reflect.io.File("/tmp/sample.txt").exists
    

    works as well.

    0 讨论(0)
  • 2020-12-05 22:59

    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"))
    
    0 讨论(0)
  • 2020-12-05 23:08

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

    scala> new java.io.File("/tmp").exists
    res0: Boolean = true
    
    0 讨论(0)
  • 2020-12-05 23:09

    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
    
    0 讨论(0)
提交回复
热议问题