Is there a good "scala-esque" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?
For example recursively all files matching "a*.foo"
in c:\temp
.
The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well. Options listed below may be preset in the DIRCMD environment variable. To override preset options, prefix any switch with - (hyphen), for example, "/-W".
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
In a computer file system, a subdirectory is a directory that is contained another directory, called a parent directory. A parent directory may have multiple subdirectories. In operating systems with a GUI such as Microsoft Windows, a directory is called a folder, and a subdirectory is called a subfolder.
Scala code typically uses Java classes for dealing with I/O, including reading directories. So you have to do something like:
import java.io.File def recursiveListFiles(f: File): Array[File] = { val these = f.listFiles these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles) }
You could collect all the files and then filter using a regex:
myBigFileArray.filter(f => """.*\.html$""".r.findFirstIn(f.getName).isDefined)
Or you could incorporate the regex into the recursive search:
import scala.util.matching.Regex def recursiveListFiles(f: File, r: Regex): Array[File] = { val these = f.listFiles val good = these.filter(f => r.findFirstIn(f.getName).isDefined) good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_,r)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With