Reading files from a directory in Scala

后端 未结 4 1227
深忆病人
深忆病人 2020-12-23 18:20

How do I get the list of files (or all *.txt files for example) in a directory in Scala. The Source class does not seem to help.

相关标签:
4条回答
  • 2020-12-23 18:25

    The Java File class is really all you need, although it's easy enough to add some Scala goodness to iteration over directories easier.

    import scala.collection.JavaConversions._
    
    for(file <- myDirectory.listFiles if file.getName endsWith ".txt"){
       // process the file
    }
    
    0 讨论(0)
  • 2020-12-23 18:29

    The JDK7 version, using the new DirectoryStream class is:

    import java.nio.file.{Files, Path}
    Files.newDirectoryStream(path)
        .filter(_.getFileName.toString.endsWith(".txt"))
        .map(_.toAbsolutePath)
    

    Instead of a string, this returns a Path, which has loads of handy methods on it, like 'relativize' and 'subpath'.

    Note that you will also need to import import scala.collection.JavaConversions._ to enable interop with Java collections.

    0 讨论(0)
  • 2020-12-23 18:34
    new java.io.File(dirName).listFiles.filter(_.getName.endsWith(".txt"))
    
    0 讨论(0)
  • 2020-12-23 18:41

    For now, you should use Java libraries to do so.

    0 讨论(0)
提交回复
热议问题