Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active March 9, 2018 10:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save frgomes/fc9e3bf54885dec1ad6c to your computer and use it in GitHub Desktop.
Save frgomes/fc9e3bf54885dec1ad6c to your computer and use it in GitHub Desktop.
Scala - List files recursively
trait FileSystem {
import java.io.File
import scala.util.matching.Regex
final def listFiles(base: File, recursive: Boolean = true): Seq[File] = {
val files = base.listFiles
val result = files.filter(_.isFile)
result ++
files
.filter(_.isDirectory)
.filter(_ => recursive)
.flatMap(listFiles(_, recursive))
}
final def listClasses(base: File, regex: Regex, recursive: Boolean = true) : Seq[IndexedSeq[String]] =
listFiles(base)
.filter(f => regex.findFirstIn(f.getAbsolutePath).isDefined)
.map(f => regex.findFirstMatchIn(f.getAbsolutePath))
.flatten
.map(m => m.subgroups.toIndexedSeq)
}
val base : String = "/home/rgomes/workspace/alpha1"
val regex : Regex = """(.*)(/src/main/java/)(([A-Za-z0-9_]+/)*)([A-Za-z0-9_]+)(\.java)$""".r
val entities =
listClasses(new File(base), regex)
.map(p => (p(4) + p(5)).replaceAll("/","."))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment