1. Overview

As we know, software development requires file manipulation and file system structure administration, especially in Scala, with many big data applications.

In this tutorial, we’ll look at three approaches to deleting a directory recursively — that is, deleting everything under the directory tree.

2. Using Recursion

Using another approach, we can delete every file under the main path.

To achieve this, we can use recursion because every directory may have one or more files. But also, any directory might have another directory to which the same rule applies.

So, let’s create a method that receives a directory as a Java File, searches for every file under this path, and recursively deletes them:

def deleteRecursively(file: File): Unit = {
  if (file.isDirectory) {
    file.listFiles.foreach(deleteRecursively)
  }
  if (file.exists && !file.delete) {
    throw new Exception(s"Unable to delete ${file.getAbsolutePath}")
  }
}

The first if-structure validates if the input is a directory — if it is, it’ll apply the delete method again for every subdirectory or file in it.

The second if-structure validates if the file exists, then it deletes the file and validates if the deletion occurred successfully. We use the delete method, which works similarly to deleteRecursively method, returning a boolean true for success and false for failure.

As a result, this implementation will go through every file in every directory under the leading directory, deleting every file.

3. Using NIO API

Also, in Java, we have the NIO API, which stands for New I/O.

To delete recursively utilizing this NIO, we create rules defining the actions when handling files and directories. So, when going through all subdirectories and files in a leading directory, it will execute the action. In this case, it’ll delete the file or directory. Let’s take a look:

def deleteNio(root: Path): Unit = {
  Files.walkFileTree(
    root,
    new SimpleFileVisitor[Path] {
      override def visitFile(
        file: Path,
        attrs: BasicFileAttributes
      ): FileVisitResult = {
        Files.delete(file)
        FileVisitResult.CONTINUE
      }
      override def postVisitDirectory(
        dir: Path,
        exc: IOException
      ): FileVisitResult = {
        Files.delete(dir)
        FileVisitResult.CONTINUE
      }
    }
  )
}

As we can see, starting with the root path, we’ll walk through each file or directory and delete utilizing the method delete from NIO File.

4. Conclusion

In this article, we’ve seen three approaches to deleting all files given an input directory recursively in Scala. One utilizes Scala language implementation, and another uses recursion to achieve multiple deletions on each file. And the third one uses a newer Java I/O API (NIO) to delete all files, defining a set of rules to apply when visiting the files and subdirectories.