从提供的目录中的文件名创建字符串列表
create list of String from file names in provided directory
可能我的问题很明显。想查看一个目录并创建字符串列表,其中每个字符串代表存储在给定目录中的文件名,例如列表("file1.csv", "file2.csv", "file3.csv").
我使用创建列表的函数,但它是文件列表(不是字符串)并且包括完整路径(不仅是文件名)。
import java.io.File
def 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
}
}
谢谢你的所有想法。
您可以使用 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
}
}
尝试将 getFileNames
的 return 类型更改为 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
之后。
better-files 会将其简化为
import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)
可能我的问题很明显。想查看一个目录并创建字符串列表,其中每个字符串代表存储在给定目录中的文件名,例如列表("file1.csv", "file2.csv", "file3.csv").
我使用创建列表的函数,但它是文件列表(不是字符串)并且包括完整路径(不仅是文件名)。
import java.io.File
def 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
}
}
谢谢你的所有想法。
您可以使用 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
}
}
尝试将 getFileNames
的 return 类型更改为 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
之后。
better-files 会将其简化为
import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)