How do I list all files in a subdirectory in scala?

后端 未结 19 1491
旧巷少年郎
旧巷少年郎 2020-11-28 03:35

Is there a good \"scala-esque\" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?

For example re

19条回答
  •  庸人自扰
    2020-11-28 04:11

    As of Java 1.7 you all should be using java.nio. It offers close-to-native performance (java.io is very slow) and has some useful helpers

    But Java 1.8 introduces exactly what you are looking for:

    import java.nio.file.{FileSystems, Files}
    import scala.collection.JavaConverters._
    val dir = FileSystems.getDefault.getPath("/some/path/here") 
    
    Files.walk(dir).iterator().asScala.filter(Files.isRegularFile(_)).foreach(println)
    

    You also asked for file matching. Try java.nio.file.Files.find and also java.nio.file.Files.newDirectoryStream

    See documentation here: http://docs.oracle.com/javase/tutorial/essential/io/walk.html

提交回复
热议问题