1

probably my question is rather obvious. Would like to look on the one directory and createthe the List of the String, where each string represents the file name stored in given direcotry, e.g. List("file1.csv", "file2.csv", "file3.csv").

I use the function which creates list, but it's list of Files (not Strings) and includes full paths (not only the file names).

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
  }
}

Thank you for all the ideas.

2 Answers 2

2

Try changing the return type of getFileNames toList[String] and use map(_.getName) like so

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
    }
  }

Make sure .map(_.getName) is the last in the chain, that is, after sortBy.

better-files would simplify this to

import better.files._
import better.files.Dsl._
val file = file"."
ls(file).toList.filter(_.isRegularFile).map(_.name)
Sign up to request clarification or add additional context in comments.

Comments

1

you can use getName method

and as Tomasz pointed out, filter and map can be combined to collect as following

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
  }
}

2 Comments

The filter followed by map can be combined using collect collect{ case f if f.isFile => f.getName }
Thanks! A small comment: the output type should be changed to the List[String].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.