Practical Scala; Walking a tree directory

One of my requirements for botlist is to have a searchable help system. E.g. instead of man pages or Java API. I want to be able to add files to a directory. Index the files in the directory and then have the data as searchable. All of this through a command line interface. I started some initial code and used the following Scala idioms:

First Version, use of File Class:


class DocWalkFile(file: File) {
def children = new Iterable[File] {
def elements =
if (file.isDirectory) file.listFiles.elements else Iterator.empty;
}
def andTree : Iterable[File] = (
Seq.single(file) ++ children.flatMap(child => new DocWalkFile(child).andTree))
}
def listDocuments(dir: File): List[File] =
(new DocWalkFile(dir)).andTree.toList filter (f => (f.getName.endsWith(".java") || f.getName.endsWith(".txt")))



Second Version:

import java.io.File

object DocWalkFile {
def andTree(dir: File): List[File] = {
val fileList = dir.listFiles.toList
(fileList filter(f => f.isFile && f.getName.endsWith(".txt"))) :::
(fileList filter(f => f.isDirectory) flatMap (f => andTree(f) ))
}
def main(args: Array[String]): Unit = {
if (args length == 0)
println("usage: DocWalkFile [dir]")
else {
println("using dir " + args.apply(0));
andTree(new
File(args.apply(0))).foreach(f => println(">> " + f))
}
}

}
Resources:


Comments

Popular posts from this blog

Is Java the new COBOL? Yes. What does that mean, exactly? (Part 1)

On Unit Testing, Java TDD for developers to write

JVM Notebook: Basic Clojure, Java and JVM Language performance