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.

Pimgd
22.5k5 gold badges68 silver badges144 bronze badges
asked Feb 5, 2016 at 10:40
\$\endgroup\$

1 Answer 1

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
 }
}
answered Feb 5, 2016 at 12:07
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.