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
  • 51,689
  • 8
  • 120
  • 144
jahilldev
  • 3,271
  • 4
  • 31
  • 47

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
  • 57,883
  • 20
  • 169
  • 230
  • 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
  • 34,093
  • 11
  • 73
  • 117