面试题答案
一键面试设计思路
- 使用Kotlin的NIO(
java.nio
包)中的Path
和Files
类来处理文件路径和文件操作。 - 采用
BufferedReader
包装InputStreamReader
,通过Files.newBufferedReader
方法创建,这样可以提高读取效率。 - 逐行读取文件内容,对每一行进行单词拆分,然后统计特定单词出现的次数。
核心代码
import java.nio.file.Path
import java.nio.file.Paths
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
fun countWordInLargeFile(filePath: String, targetWord: String): Int {
var count = 0
val path: Path = Paths.get(filePath)
Files.newBufferedReader(path, StandardCharsets.UTF_8).use { reader: BufferedReader ->
var line: String?
while (reader.readLine().also { line = it } != null) {
val words = line!!.split("\\s+".toRegex())
for (word in words) {
if (word == targetWord) {
count++
}
}
}
}
return count
}
你可以使用以下方式调用这个函数:
fun main() {
val filePath = "your_10GB_file.txt"
val targetWord = "specific_word"
val result = countWordInLargeFile(filePath, targetWord)
println("The word '$targetWord' appears $result times.")
}