Delete files and subdirectories in a directory in Kotlin
This post will discuss how to delete files and subdirectories in a directory in Kotlin.
The standard function to delete the specified file or directory in Kotlin is File.delete(). There are several options to “conditionally” delete files and subdirectories within a directory using this function. For instance,
1. To delete only regular files within the root directory, you can do as follows.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.io.File fun deleteDirectory(directory: File) { for (file in directory.listFiles()) { if (!file.isDirectory) { file.delete() } } } fun main() { val directory = File("/path/to/dir") deleteDirectory(directory) } |
Note that all subdirectories remain untouched. You can replace the for loop with the stdlib operations filterNot{}.forEach{}.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.File fun deleteDirectory(directory: File) { directory.listFiles() .filterNot { it.isDirectory } .forEach { it.delete() } } fun main() { val directory = File("/path/to/dir") deleteDirectory(directory) } |
2. To delete a subdirectory with the File.delete() function, it should be empty. The idea is to recursively delete all files within the subdirectory, before deleting the subdirectory itself. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.File import java.util.* fun deleteDirectory(directory: File) { for (file in directory.listFiles()) { if (file.isDirectory) { deleteDirectory(file) } else { file.delete() } } } fun main() { val directory = File("/path/to/dir") deleteDirectory(directory) } |
3. Alternatively, to delete the main directory as well (and all its contents), use the Files.walk() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.nio.file.Files import java.nio.file.Path fun deleteDirectory(directory: Path?) { Files.walk(directory) .sorted(Comparator.reverseOrder()) .map { it.toFile() } .forEach { it.delete() } } fun main() { val directory = Path.of("/path/to/dir") deleteDirectory(directory) } |
If you need to delete “only files” from the directory and all its subdirectories, apply a filter as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.io.File import java.nio.file.Files fun deleteDirectory(directory: File) { Files.walk(directory.toPath()) .filter { Files.isRegularFile(it) } .map { it.toFile() } .forEach { it.delete() } } fun main() { val directory = File("/path/to/dir") deleteDirectory(directory) } |
That’s all about deleting files and subdirectories in a directory in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)