从 Scala 目录中读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8622364/
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 03:46:24  来源:igfitidea点击:

Reading files from a directory in Scala

scala

提问by snappy

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.

如何获取 Scala 目录中的文件列表(例如,或所有 *.txt 文件)。Source 类似乎没有帮助。

回答by huynhjl

new java.io.File(dirName).listFiles.filter(_.getName.endsWith(".txt"))

回答by Nick Cecil

The JDK7 version, using the new DirectoryStream class is:

JDK7 版本,使用新的 DirectoryStream 类是:

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'.

这不是一个字符串,而是返回一个 Path,它上面有很多方便的方法,比如 'relativize' 和 'subpath'。

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

请注意,您还需要导入import scala.collection.JavaConversions._以启用与 Java 集合的互操作。

回答by Dave Griffith

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

Java File 类确实是您所需要的,尽管添加一些 Scala 优点来更轻松地遍历目录也很容易。

import scala.collection.JavaConversions._

for(file <- myDirectory.listFiles if file.getName endsWith ".txt"){
   // process the file
}

回答by Daniel C. Sobral

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

现在,您应该使用 Java 库来执行此操作。