MST

星途 面试题库

面试题:Kotlin的NIO优化在大文件处理中的应用

假设你需要处理一个非常大的文本文件(例如10GB),使用Kotlin的NIO方式,如何高效地读取文件内容并统计其中某个特定单词出现的次数?请阐述你的设计思路并写出核心代码。
20.1万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 使用Kotlin的NIO(java.nio包)中的PathFiles类来处理文件路径和文件操作。
  2. 采用BufferedReader包装InputStreamReader,通过Files.newBufferedReader方法创建,这样可以提高读取效率。
  3. 逐行读取文件内容,对每一行进行单词拆分,然后统计特定单词出现的次数。

核心代码

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.")
}