Creare un file watcher in Scala

Mattepuffo's logo
Creare un file watcher in Scala

Creare un file watcher in Scala

In questo articolo vediamo come creare un filesystem watcher in Scala 3.

Non abbiamo dipendenze da installare.

Ecco il codice:

package org.example

import java.nio.file.{FileSystems, Paths, StandardWatchEventKinds, Path}
import scala.jdk.CollectionConverters._

@main
def main(): Unit = {
  val watchPath = Paths.get("/home/fermat/TEST/")
  val watchService = FileSystems.getDefault.newWatchService()

  watchPath.register(
    watchService,
    StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_MODIFY,
    StandardWatchEventKinds.ENTRY_DELETE
  )

  println(s"Watching directory: $watchPath")
  println("Press Ctrl+C to stop watching...")

  var running = true
  while running do
    val key = watchService.take()

    for event <- key.pollEvents().asScala do
      val kind = event.kind()
      val filename = event.context().asInstanceOf[Path]
      val fullPath = watchPath.resolve(filename)

      kind match
        case StandardWatchEventKinds.ENTRY_CREATE =>
          println(s"CREATED: $fullPath")
        case StandardWatchEventKinds.ENTRY_MODIFY =>
          println(s"MODIFIED: $fullPath")
        case StandardWatchEventKinds.ENTRY_DELETE =>
          println(s"DELETED: $fullPath")
        case _ =>
          println(s"OTHER EVENT: $fullPath")

    if !key.reset() then
      running = false
}

Enjoy!


Condividi

Commentami!