Skip to content

Instantly share code, notes, and snippets.

@gekomad
Last active February 4, 2020 12:23
Show Gist options
  • Save gekomad/cd2f326a101ff5ec694b9bf5dca71c6f to your computer and use it in GitHub Desktop.
Save gekomad/cd2f326a101ff5ec694b9bf5dca71c6f to your computer and use it in GitHub Desktop.
Get a list of files that are in a directory and subdirectories
def recursiveListFiles(f: File): ArraySeq[File] = {
val these = f.listFiles
ArraySeq.from(these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles))
}
///
import java.io.File
def getListOfFiles(dir: String): List[File] = {
def go(dir: File): List[File] = dir match {
case d if d.exists && d.isDirectory && d.canRead=>
val files = d.listFiles.filter(a => a.canRead && a.isFile).toList
val dirs = dir.listFiles.filter(_.isDirectory).toList
files ::: dirs.foldLeft(List.empty[File])(_ ::: go(_))
case _ => List.empty[File]
}
go(new File(dir))
}
// using cats
import java.io.File
import cats.effect.IO
def getListOfFiles(dir: String): IO[List[File]] = {
def go(dir: File): List[File] = dir match {
case d if d.exists && d.isDirectory =>
if (d.canRead) {
val files = d.listFiles.filter(_.isFile).toList
val dirs = dir.listFiles.filter(_.isDirectory).toList
files ::: dirs.foldLeft(List.empty[File])(_ ::: go(_))
} else throw new IOException(s"Error opening directory '$d': Permission denied")
case _ => List.empty[File]
}
IO.fromTry(Try(go(new File(dir))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment