可能我的问题很明显。想要查看一个目录并创建字符串列表,其中每个字符串代表存储在给定目录中的文件名,例如 List("file1.csv", "file2.csv", "file3.csv")。我使用创建列表的函数,但它是文件列表(不是字符串)并且包括完整路径(不仅是文件名)。import java.io.Filedef getFileNames(path: String): List[File] = { val d = new File(path) if (d.exists && d.isDirectory) { d .listFiles // create list of File .filter(_.isFile) .toList .sortBy(_.getAbsolutePath().replaceAll("[^a-zA-Z0-9]","")) } else { Nil // return empty list }}
2 回答
侃侃尔雅
TA贡献1801条经验 获得超15个赞
getFileNames尝试更改to的返回类型并像这样List[String]使用map(_.getName)
def getFileNames(path: String): List[String] = {
val d = new File(path)
if (d.exists && d.isDirectory) {
d
.listFiles // create list of File
.filter(_.isFile)
.toList
.sortBy(_.getAbsolutePath().replaceAll("[^a-zA-Z0-9]",""))
.map(_.getName)
} else {
Nil // return empty list
}
}
确保.map(_.getName)是链中的最后一个,即在 之后sortBy。
更好的文件会将其简化为
import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
你可以使用 getName 方法
正如 Tomasz 指出的那样,过滤器和地图可以组合起来收集如下
def getFileNames(path: String): List[String] = { val d = new File(path) if (d.exists && d.isDirectory) { d .listFiles // create list of File .collect{ case f if f.isFile => f.getName }// gets the name of the file <-- .toList .sortBy(_.getAbsolutePath().replaceAll("[^a-zA-Z0-9]","")) } else { Nil // return empty list } }
添加回答
举报
0/150
提交
取消