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
?
Try this code that throws an exception if it fails:
You could also fold or map over the delete if you want to return a value for all the deletes.
What I ended up with
Getting little lengthy, but here's one that combines the recursivity of Garrette's solution with the npe-safety of the original question.
Using scala IO
or better, you could use a
Try
which will either result in a
Success[Int]
containing the number of files deleted, or aFailure[IOException]
.This one uses java.io but one can delete directories matching it with wildcard string which may or may not contain any content within it.
Directory structure e.g. * A/1/, A/2/, A/300/ ... thats why the regex String: [1-9]*, couldn't find a File API in scala which supports regex(may be i missed something).
This is recursive method that clean all in directory, and return count of deleted files