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
?
Using java 6 without using dependencies this is pretty much the only way to do so.
The problem with your function is that it return Unit (which I btw would explicit note it using
def delete(file: File): Unit = {
I took your code and modify it to return map from file name to the deleting status.
Expanding on Vladimir Matveev's NIO2 solution:
With pure scala + java way
From http://alvinalexander.com/blog/post/java/java-io-faq-how-delete-directory-tree
Using Apache Common IO
The Scala one can just do this...
Maven Repo Imports
Using the Java NIO.2 API:
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.To add to Slavik Muz's answer: