Two distinct parts:
- Obtain a file that represents the resource directory
- Traverse the directory
For 1 you can use Java's getResource
:
val dir = File( object {}.javaClass.getResource(directoryPath).file )
For 2 you can use Kotlin's File.walk
extension function that returns a sequence of files which you can process, e.g:
dir.walk().forEach { f ->
if(f.isFile) {
println("file ${f.name}")
} else {
println("dir ${f.name}")
}
}
Put together you may end up with the following code:
fun onEachResource(path: String, action: (File) -> Unit) {
fun resource2file(path: String): File {
val resourceURL = object {}.javaClass.getResource(path)
return File(checkNotNull(resourceURL, { "Path not found: '$path'" }).file)
}
with(resource2file(path)) {
this.walk().forEach { f -> action(f) }
}
}
so that if you have resources/nested
direcory, you can:
fun main() {
val print = { f: File ->
when (f.isFile) {
true -> println("[F] ${f.absolutePath}")
false -> println("[D] ${f.absolutePath}")
}
}
onEachResource("/nested", print)
}