Delete directory recursively in Scala

32,875

Solution 1

With pure scala + java way

import scala.reflect.io.Directory
import java.io.File

val directory = new Directory(new File("/sampleDirectory"))
directory.deleteRecursively()

deleteRecursively() Returns false on failure

Solution 2

Try this code that throws an exception if it fails:

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}")
  }
}

You could also fold or map over the delete if you want to return a value for all the deletes.

Solution 3

Using scala IO

import scalax.file.Path

val path = Path.fromString("/tmp/testfile")    
try {
  path.deleteRecursively(continueOnFailure = false) 
} catch {
  case e: IOException => // some file could not be deleted
}

or better, you could use a Try

val path: Path = Path ("/tmp/file")
Try(path.deleteRecursively(continueOnFailure = false))

which will either result in a Success[Int] containing the number of files deleted, or a Failure[IOException].

Solution 4

From http://alvinalexander.com/blog/post/java/java-io-faq-how-delete-directory-tree

Using Apache Common IO

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public void deleteDirectory(String directoryName)
throws IOException
{
  try
  {
    FileUtils.deleteDirectory(new File(directoryName));
  }
  catch (IOException ioe)
  {
    // log the exception here
    ioe.printStackTrace();
    throw ioe;
  }
}

The Scala one can just do this...

import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.WildcardFileFilter
FileUtils.deleteDirectory(new File(outputFile))

Maven Repo Imports

Solution 5

Using the Java NIO.2 API:

import java.nio.file.{Files, Paths, Path, SimpleFileVisitor, FileVisitResult}
import java.nio.file.attribute.BasicFileAttributes

def remove(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
    }
  })
}

remove(Paths.get("/tmp/testdir"))

Really, it's a pity that the NIO.2 API is with us for so many years and yet few people are using it, even though it is really superior to the old File API.

Share:
32,875
Michael
Author by

Michael

Scala (moslty) programmer

Updated on July 31, 2022

Comments

  • Michael
    Michael almost 2 years

    I am writing the following (with Scala 2.10 and Java 6):

    import java.io._
    
    def delete(file: File) {
      if (file.isDirectory) 
        Option(file.listFiles).map(_.toList).getOrElse(Nil).foreach(delete(_))
      file.delete
    }
    

    How would you improve it ? The code seems working but it ignores the return value of java.io.File.delete. Can it be done easier with scala.io instead of java.io ?