Skip to main content

How to delete a directory in Kotlin

How to delete a directory in Kotlin.

Here's a step-by-step tutorial on how to delete a directory in Kotlin:

  1. First, import the necessary classes from the java.nio.file package:
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
  1. Next, define the path of the directory you want to delete:
val directoryPath = Paths.get("/path/to/directory")

Replace "/path/to/directory" with the actual path of the directory you want to delete.

  1. Before deleting the directory, make sure it exists. You can use the Files.exists() method to check if the directory exists:
if (Files.exists(directoryPath)) {
// Directory exists, proceed with deletion
} else {
// Directory does not exist, handle error or exit
}
  1. To delete the directory, use the Files.delete() method:
try {
Files.delete(directoryPath)
println("Directory deleted successfully.")
} catch (e: IOException) {
println("Failed to delete directory: ${e.message}")
}
  1. If the directory contains subdirectories or files, the Files.delete() method will throw a DirectoryNotEmptyException. To delete the directory and its contents recursively, you can use the Files.walkFileTree() method:
try {
Files.walkFileTree(directoryPath, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}

override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
println("Directory deleted successfully.")
} catch (e: IOException) {
println("Failed to delete directory: ${e.message}")
}

In this example, we override the visitFile() method to delete each file encountered and the postVisitDirectory() method to delete each directory after all its contents have been processed.

That's it! You now know how to delete a directory in Kotlin.