Scala - Deleting a Directory


Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read, write, delete files and directories, etc.

Deleting a Directory

Deleting a directory in Scala can be done similarly to deleting a file. However, the directory must be empty to be deleted using the delete method.

Example

Following is the example which shows you how to delete an empty directory named testDir

import java.io._

object Demo {
   def main(args: Array[String]) = {
      val directory = new File("testDir")
      
      if (directory.delete()) {
         println("Directory deleted successfully")
      } else {
         println("Failed to delete the directory")
      }
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code will attempt to delete the directory testDir. If the directory is empty and is deleted successfully, it will print "Directory deleted successfully". If the directory is not empty or the deletion fails for some reason, it will print "Failed to delete the directory".

This will produce the following result -

Directory deleted successfully

Deleting Non-Empty Directory

To delete a non-empty directory, you need to first delete all the files and subdirectories inside it.

Example

Following is the example which shows you how to delete a non-empty directory named nonEmptyDir

import java.io._

object Demo {
   def main(args: Array[String]) = {
      val directory = new File("nonEmptyDir")
      
      if (deleteDirectory(directory)) {
         println("Non-empty directory deleted successfully")
      } else {
         println("Failed to delete the non-empty directory")
      }
   }

   def deleteDirectory(directory: File): Boolean = {
      if (directory.isDirectory) {
         val children = directory.list()
         if (children != null) {
            for (child <- children) {
               val success = deleteDirectory(new File(directory, child))
               if (!success) {
                  return false
               }
            }
         }
      }
      directory.delete()
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code will attempt to delete the directory nonEmptyDir and all its contents. If the directory and all its contents are deleted successfully, it will print "Non-empty directory deleted successfully". If the deletion fails for some reason, it will print "Failed to delete the non-empty directory".

This will produce the following result -

Non-empty directory deleted successfully

Deleting Directories with Wildcards

You can delete multiple directories matching a certain pattern using wildcards.

Example

Following is the example which shows you how to delete all directories that start with tempDir

import java.io._

object Demo {
   def main(args: Array[String]) = {
      val directory = new File(".")

      val tempDirs = directory.listFiles(new FilenameFilter {
         def accept(dir: File, name: String): Boolean = 
            name.startsWith("tempDir") && new File(dir, name).isDirectory
      })

      if (tempDirs != null) {
         for (dir <- tempDirs) {
            if (deleteDirectory(dir)) {
               println(s"Directory ${dir.getName} deleted successfully")
            } else {
               println(s"Failed to delete directory ${dir.getName}")
            }
         }
      }
   }

   def deleteDirectory(directory: File): Boolean = {
      if (directory.isDirectory) {
         val children = directory.list()
         if (children != null) {
            for (child <- children) {
               val success = deleteDirectory(new File(directory, child))
               if (!success) {
                  return false
               }
            }
         }
      }
      directory.delete()
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code will attempt to delete all directories starting with tempDir in the current directory. For each directory, it will print either "Directory dirname deleted successfully" if the deletion succeeds, and "Failed to delete directory dirname" if the deletion fails.

This will produce the following result -

Directory tempDir1 deleted successfully
Directory tempDir2 deleted successfully

Handling Exceptions When Deleting Directories

When working with file operations, it is important to handle exceptions like SecurityException to make your code more robust.

Example

Following is the example which shows you how to handle exceptions when deleting a directory −

import java.io._

object Demo {
   def main(args: Array[String]) = {
      try {
         val directory = new File("testDir")
         
         if (directory.delete()) {
            println("Directory deleted successfully")
         } else {
            println("Failed to delete the directory")
         }
      } catch {
         case ex: SecurityException => println("Permission denied: " + ex.getMessage)
         case ex: IOException => println("An IO error occurred: " + ex.getMessage)
      }
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

If an error occurs, the program will print an appropriate error message.

This will produce the following result -

Permission denied: [error message]