如何在kotlin中编写递归协程

我想写一个更快的文件搜索器在kotlin找到我的主文件夹下的所有文本文件。

这是我的代码序列搜索

import java.io.File import java.util.concurrent.atomic.AtomicLong var count: AtomicLong = AtomicLong(0) fun main(args: Array<String>) { println(System.getProperty("user.home")) val start = System.currentTimeMillis() findTxtFile(System.getProperty("user.home") + "/git", ".txt") println("took: " + (System.currentTimeMillis() - start)) println(count.get()) } fun findTxtFile(path: String, extension: String) { File(path).listFiles().forEach { if (it.isDirectory) { findTxtFile(it.absolutePath, extension) } else if (it.name.endsWith(extension)) { count.getAndIncrement() } } } 

我下面写了一个程序,但是当你有很多文件的时候,会抛出NullPointerException,怎么可能抛出空指针异常呢?

 import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.runBlocking import java.io.File fun main(args: Array<String>) { val start = System.currentTimeMillis() var filePath = System.getProperty("user.home") var deferred = File(filePath).listFiles().map { path -> async(CommonPool) { findTxtFile(path.absolutePath) } } runBlocking { deferred.map { it.await() } } println((System.currentTimeMillis() - start) / 1000) } suspend fun findTxtFile(path: String) { //println("--------------------- $path") if (File(path).isDirectory) { File(path).listFiles().forEach { findTxtFile(it.absolutePath) //===> Exception happen here } } else if (path.endsWith(".java")) { println(path) } }