Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Count number of files in directory with defined file extension

Tags:

file

scala

Hi I have a script which batch converts pdfs into a series of images, what I'd like to do is count the total number of files in the directory that have the extension .jpg.

So far I have

for (file <- new File(path).listFiles) {

     /* DO SOMETHING */

}

Is there a compact way of doing this without looping through each file?

Thanks in advance, much appreciated :)

like image 941
jahilldev Avatar asked Mar 01 '12 16:03

jahilldev


Video Answer


1 Answers

How about:

Option(new File(path).list).map(_.filter(_.endsWith(".jpg")).size).getOrElse(0)

Option(...) acts as a null check and is needed because list and listFiles may return null.

like image 186
Jean-Philippe Pellet Avatar answered Oct 14 '22 17:10

Jean-Philippe Pellet