5

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 :)

dhg
  • 52,383
  • 8
  • 123
  • 144
jahilldev
  • 3,520
  • 4
  • 35
  • 52

2 Answers2

8

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.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • Learned something new. Thanks. I'd personally break it into 2-3 lines though. I think One-liners are usually harder to read. – Jesse Mar 01 '12 at 22:56
0
for (file <- new java.io.File (".").listFiles;
  if (file.getName ().matches (".*\\.scala"))) println (file)

results in:

./TopTen.scala
./QuadTree.scala
./Euler093.scala
./ParallelFactorial.scala
./GenericCartesian.scala
user unknown
  • 35,537
  • 11
  • 75
  • 121