質問

def recursiveTotalDirectorySize(dir: File): Long = {
    var totalFileSize = 0L;
    val (dirs, files) = dir.listFiles.partition(_.isDirectory)

    if (dirs.length > 0) dirs.foreach((f: File) => totalFileSize += recursiveTotalDirectorySize(f))

    if (files.length > 0) totalFileSize += files.map((f: File) => f.length()).reduceLeft(_ + _)

    totalFileSize
}

Do you have a better solution for total file size recursion using Scala. What are your comments for this. Thanks!

役に立ちましたか?

解決

One liner, no mutable vars, parallelizes the processing of each entry in a directory

  def recursiveTotalDirectorySize(dir: File): Long =
  dir.listFiles.par.map{
     f => if (f.isDirectory) recursiveTotalDirectorySize(f) else f.length()
  }.sum

他のヒント

A similar approach, using foldLeft,

def dirSize(dir: File): Long = 
  ( 0L /: dir.listFiles) { (sum,f) => sum + 
    (if (f.isDirectory) dirSize(f) else f.length) }

Accepted answer has the potential quality of using par.map; here par.aggregate may prove equivalent,

def dirSize(dir: File): Long = 
  dir.listFiles.par.aggregate(0L)((sum,f) => sum + 
    (if (f.isDirectory) dirSize(f) else f.length), _+_)

In fact par.aggregate may be seen as a form of MapReduce.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top