\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
}
}
lang-scala