我想在 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)
}
}