【问题标题】:create list of String from file names in provided directory从提供的目录中的文件名创建字符串列表
【发布时间】:2019-06-26 21:35:53
【问题描述】:

可能我的问题很明显。想查看一个目录并创建字符串列表,其中每个字符串代表存储在给定目录中的文件名,例如列表(“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
  }
}

感谢您的所有想法。

【问题讨论】:

    标签: java scala file-io


    【解决方案1】:

    尝试将getFileNames 的返回类型更改为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)
    

    【讨论】:

      【解决方案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
        }
      }
      

      【讨论】:

      • filter 后跟 map 可以使用 collect collect{ case f if f.isFile =&gt; f.getName } 组合起来
      • 谢谢!一个小注释:输出类型应该改为List[String]。
      猜你喜欢
      • 1970-01-01
      • 2016-05-14
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2020-07-11
      • 2022-11-16
      • 2020-04-21
      相关资源
      最近更新 更多