3
\$\begingroup\$

I have written a code to count the number of files in a folder and if there are any folder inside folder it will count the files in that folder too.

import java.io.File
class GetFileCount {
  def getFilesCount(dir: String):Int = {
    val file = new File(dir)
    require(file.exists() && file.isDirectory)
    def inDirectoryFiles(inDir:List[File]):Int={
      if(inDir.filter(_.isDirectory).nonEmpty)
        inDir.filter(_.isFile).length + inDirectoryFiles(inDir.flatMap(_.listFiles.toList))
      else
        inDir.filter(_.isFile).length
    }
    file.listFiles.filter(_.isFile).toList.length + inDirectoryFiles(file.listFiles.filter(_.isDirectory).toList)
  }
}

I feel like it could be done more nicely.

\$\endgroup\$
1
\$\begingroup\$

If you are allowed to, I would strongly suggest using https://github.com/pathikrit/better-files to do this. The code would look like :

import better.files._
class GetFileCount {
  def getFilesCount(dir: String):Int = {
    File(dir).glob("**").count(_.isRegularFile)        
  }
}

If you can't or won't use better-files, you can probably improve your code using just nio:

import java.nio.file.{ FileSystems, Paths, Path, Files }
import java.util.function.Predicate
import java.util.stream.Stream
object GetFileCount{
  val regularFilePredicate = new Predicate[Path] {
    override def test(path: Path) = Files.isRegularFile(path)
  }
}
class GetFileCount {
  import GetFileCount._
  def getFilesCount(dir: String): Int = {
    val path: Path = FileSystems.getDefault.getPath("/tmp/d1")
    val filter: Stream[Path] = Files.walk(path).filter(regularFilePredicate)
    filter.toArray.length
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.