jahilldev
jahilldev

Reputation: 3812

Scala - Remove files from folder by file suffix name

I'm looking for an elegant way to remove all files in a folder that have the extension .jpg

I have the following to count the total jpg files in a folder:

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

Thanks in advance, any help much appreciated :)

Upvotes: 4

Views: 5623

Answers (3)

Powers
Powers

Reputation: 19308

os-lib lets you delete all files with a certain extension with a one liner:

os.list(os.pwd/"pics").filter(_.ext == "jpg").map(os.remove)

As described here, os-lib is the easiest way to perform filesystem operations with Scala. It lets you write beautiful, concise, Scala code without dealing with ugliness of the underlying Java libs.

Here's some setup code if you'd like to test this out on your machine:

os.makeDir(os.pwd/"pics")
os.write(os.pwd/"pics"/"family.jpg", "")
os.write(os.pwd/"pics"/"cousins.txt", "")
os.write(os.pwd/"pics"/"gf.jpg", "")
os.write(os.pwd/"pics"/"friend.gif", "")

Upvotes: 0

Aaron_ab
Aaron_ab

Reputation: 3758

Some extra comment, To extend @Debilski's answer: Touching files obviously causes side effects. To make this functionally effectfull, please do something like:

def deleteFilesBySuffix[G[_]: Sync](suffix: String)(dirName: String): G[Unit] =
    Sync[G].suspend(Sync[G].fromTry(Try(for {
      files <- Option(new File(dirName).listFiles)
      file <- files if file.getName.endsWith(suffix)
    } file.delete())))

Then, You'll have to run this code with an effect which can delay the execution of this method like:

import cats.IO
import cats.syntax.foldable._

val r = deleteFilesBySuffix[IO]("jpg")("/tmp")
//Still nothing happened

//Another example with multiple dirs: 
val dirNames = List("/tmp", "/tmp/myDir")
val res = dirNames.traverse_(deleteFilesBySuffix[IO]("jpg"))

//Actually run it.. 
r.unsafeRunSunc()

//Now files are deleted.. 

In my opinion this is much safer, and uses Scala's power of effects

Upvotes: 0

Debilski
Debilski

Reputation: 67828

for {
  files <- Option(new File(path).listFiles)
  file <- files if file.getName.endsWith(".jpg")
} file.delete()

Upvotes: 12

Related Questions