Delete directory recursively in Scala

scala delete hdfs directory
java delete directory
scala create directory
scala create directory if not exists
scala check if directory exists
change directory in scala
scala list files in directory
copy files from one folder to another in scala

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 ?

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

Java: How to delete a directory tree, The delete method of the File class won't delete a directory tree, which meant that in the old days you had to write your own recursive method to  Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. The difference between File.delete() and this method are: A directory to be deleted does not have to be empty. No exceptions are thrown when a file or directory cannot be deleted.

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.

scala/io/Directory.scala, __ *\ ** ______ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2009, LAMP/EPFL ** ** __\ \/ /__/ makeTemp(prefix, suffix, dir) path.delete() path. deepList(depth) filterMap { case x: Directory => x } /** Deletes the directory recursively. Furthermore it runs recursively and deletes all files and directories inside of a target folder. How to compare files / folders. It’s pretty common scenario for developers. So what better-files library suggest for solving of this problem? Use == when you want to compare two files / directories by

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].

scala.reflect.io.File Scala Example, isFile && file.exists) { file.delete() } } def deleteDirectory(directory: String): Unit = { val dir = File(directory) if (dir.isDirectory && dir.exists) { dir.deleteRecursively() }  You need to use the rm command to remove files or directories (also known as folders) recursively. The rmdir command removes only empty directories. So you need to use rm command. rm command syntax to delete directories recursively

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

Delete directory (recursive) · GitHub, Delete directory (recursive). GitHub Gist: instantly Raw. XymonReporterTest.​scala def preVisitDirectory(dir: Path, attrs: BasicFileAttributes) = FileVisitResult. public: static void Delete(System::String ^ path); public static void Delete (string path); static member Delete : string -> unit Public Shared Sub Delete (path As String) The name of the empty directory to remove. This directory must be writable and empty.

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.

Scala: work with files & directories, Let's consider the most trivial example, when we need to delete a file Furthermore it runs recursively and deletes all files and directories  It happened that the call to "Remove-Item -force -recurse" did not delete all files and in that case the last Remove-Tree failed because the directory was not empty. That's why I came up with the new solution to first try the buggy built-in version (-force) and then manually descending into each directory and deleting "manually" what's left.

Deleting a File or Directory (The Java™ Tutorials > Essential , With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails. The Files class provides two  To remove a directory that contains other files or directories, use the following command. In the example above, you would replace "mydir" with the name of the directory you want to delete. For example, if the directory was named files, you would type rm -r files at the prompt.

Next How to Delete a Directory/Folder in Java using Recursion, We will use delete() function recursively to delete a directory/folder in java program. package com.journaldev.files; import java.io.File; /** * This utility class can be  Delete contents of a directory but keep the directory. The usecase here is to delete all the contents of the directory but keep the parent directory so that we do not need to create it again. rmdir /Q /S does not work here as it deletes the parent directory too. Rather the below commands should do the trick.

Delete a file, Delete a file called "input.txt" and delete a directory called "docs". 88 Ruby; 89 Run BASIC; 90 Rust; 91 Scala; 92 Scheme; 93 Seed7 BaCon has a DELETE instruction, that accepts FILE|DIRECTORY|RECURSIVE options. In this article, we'll illustrate how to delete a directory recursively in plain Java. We'll also look at some alternatives for deleting directories using external libraries. 2. Deleting a Directory Recursively

Comments
  • Personally, I feel that for comprehensions are much easier to read: ` for(list <- Option(file.listFiles()) ; child <- list) delete(child) `
  • What's the point of creating that Option and mapping through it? What's wrong with simple "file.listFiles.foreach(delete)"?
  • @ViliusNormantas The listFiles may return null so you need to check it for null or wrap it with Option. Moreover you probably need to distinguish b/w two cases: (1) listFiles returns an empty array and (2) listFiles returns null (I/O error occurred)
  • This is simple and clean when compared to other solutions posted here.
  • this does not work, as this gives errors error: not found: type File
  • @con , make sure to have import java.io.File
  • Nice recursive structure.
  • Thank you. I would not like to use any external dependencies though.
  • I packaged this code in a SBT project, so it's easily accessible for folks that have access to Maven: github.com/MrPowers/spark-daria/blob/master/src/main/scala/com/… Thanks!
  • One (ok admiittedly long ;) ) liner!