Last active
August 29, 2015 14:20
-
-
Save nelanka/7939945fd2753894c969 to your computer and use it in GitHub Desktop.
List files in a folder tail recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def recursiveListFiles(file: File): Array[File] = { | |
@tailrec | |
def trImpl(dirs: Array[File], files: Array[File]): Array[File] = { | |
if (dirs.isEmpty) { | |
files | |
} | |
else { | |
val (subdirs, moreFiles) = dirs.flatMap(_.listFiles).span(_.isDirectory) | |
trImpl(subdirs, files ++ moreFiles) | |
} | |
} | |
if (file.isDirectory) { | |
trImpl(Array(file), Array()) | |
} else if (file.isFile) { | |
Array(file) | |
} else { | |
Array() | |
} | |
} | |
def recursiveListFilesWithFilter(file: File, filter: FilenameFilter): Array[File] = { | |
@tailrec | |
def trImpl2(dirs: Array[File], files: Array[File]): Array[File] = { | |
if (dirs.isEmpty) files | |
else { | |
val (subdirs, moreFiles) = dirs.flatMap(_.listFiles(filter)).span(_.isDirectory) | |
trImpl2(files ++ moreFiles, subdirs) | |
} | |
} | |
if (file.isDirectory) { | |
trImpl2(Array(file), Array()) | |
} else if (file.isFile) { | |
Array(file) | |
} else { | |
Array() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment