Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list all files in a subdirectory in scala?

Tags:

scala

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.

like image 238
Nick Fortescue Avatar asked Apr 14 '10 13:04

Nick Fortescue


People also ask

How do I list files in a subdirectory?

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".

How do I list files in a directory and its subdirectories?

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.

Which directory contain a subdirectory in it?

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.


1 Answers

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)) } 
like image 135
Rex Kerr Avatar answered Oct 07 '22 08:10

Rex Kerr