Adam S
08/29/2023, 4:07 PMFile.listFiles()
, which isn't nice because it returns a nullable array.Adam S
08/29/2023, 4:09 PM└── some-dir/
├── a.txt
├── b.json
├── c.xml
└── sub-contents/
└── x.txt
I want to do
File("$basePath/some-dir").walk().maxDepth(1)
and get the files a.txt
, b.json
, c.xml
. And not some-dir
, or sub-contents
Oleg Yukhnevich
08/29/2023, 4:12 PMPath
in stdlib (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io.path/java.nio.file.-path/)
what could be usefull in your case:
1. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io.path/java.nio.file.-path/for-each-directory-entry.html
2. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io.path/java.nio.file.-path/visit-file-tree.html
3. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io.path/java.nio.file.-path/walk.html
Of course, if it’s possible to use latest Kotlin API version (not sure when they were introduced)Stephan Schröder
08/30/2023, 9:28 AMfun File.walkFiles(maxDepth: Int): List<File> =
this.walk().maxDepth(maxDepth).filter{it.isFile()}.toList()
if you don't need the number of Files is more efficient to return a Sequence of Files instead
fun File.walkFiles(maxDepth: Int): Sequence<File> =
this.walk().maxDepth(maxDepth).filter{it.isFile()}