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
?
We use the delete method, which works similarly to deleteRecursively method, returning a boolean true for success and false for failure. As a result, this implementation will go through every file in every directory under the leading directory, deleting every file.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
Using Java I/O Package listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File. delete() .
Scala doesn’t offer any different methods for working with directories, so use the listFiles method of the Java File class. For instance, this method creates a list of all files in a directory:
You can’t delete the dogs directory with os.remove (os.pwd/"dogs") because it contains files. You need to use os.remove.all (os.pwd/"dogs"). This library provides several good examples for the Scala community:
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. My website is made possible by displaying online advertisements to my visitors.
These file listing capabilities allow for idiomatic Scala file processing. You can recursively list a directory and find the largest nested file for example. You can’t delete the dogs directory with os.remove (os.pwd/"dogs") because it contains files.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With