首页 > 解决方案 > 如何从 Kotlin 中的 .txt 文件中选择随机行

问题描述

我想创建一个从 .txt 文件中随机打印一行的程序。这是我目前所处的位置,我能找到的唯一其他类似问题是其他语言。例如,random.choice()我在这个问题中找到的带有操作的 Python:如何从文本文件中选择随机行

谢谢大家的时间!

fun main() {
    val file = "text.txt"
    println(file.random("text.txt")) //This code doesn't work, I'm just illustrating what I was looking to do.
}

我认为有必要进行的编辑:我正在导入的库。

import java.io.FileReader
import kotlin.system.exitProcess
import java.io.FileWriter
import kotlin.random.Random

我学到的更多东西:

有一个函数RandomAccessFile用于我想做的确切目的,但是,我没有找到任何好的资源来说明如何在 Kotlin 中使用它。

评论编辑:我可以从文件中读取,当我这样做时,所有行都会按顺序打印。

1:我知道如何生成随机数,但是,我不知道如何将它添加到 .txt 文件中。

2:我尝试使用以下代码添加与其所在行相对应的数字,但是,此代码在 i 变量未被理解为现有数字的情况下运行时出现错误。

下方和粘贴中的代码错误,以确保整洁。 https://pastebin.com/FxFWjv37

fun main() {
    var i = 1
    println("Please input a value, type DONE when done, READ to print.")
    val loop = 0
    while (loop < 1) {
        var response = readLine()
        if (response == "DONE") {
            exitProcess(0)
        }else if (response== "READ") {
            RandomRead()
        } else {
                WriteToFile(i + response)
            i+1
        }
    }
}

错误:(23, 31) Kotlin: 不能使用提供的参数调用以下函数:

public final operator fun plus(other: Byte): Int 定义在 kotlin.Int

public final operator fun plus(other: Double): Double 定义在 kotlin.Int

public final operator fun plus(other: Float): kotlin.Int 中定义的浮点数

public final operator fun plus(other: Int): Int 定义在 kotlin.Int

public final operator fun plus(other: Long): Long 定义在 kotlin.Int

public final operator fun plus(other: Short): Int 定义在 kotlin.Int

我也尝试过:

fun main() {
    println("Please input a value, type DONE when done, READ to print.")
    val loop = 0
    while (loop < 1) {
        var response = readLine()
        if (response == "DONE") {
            exitProcess(0)
        }else if (response== "READ") {
            RandomRead()
        } else {
                WriteToFile(response)
        }
    }
}
fun WriteToFile(str: String?) {
    var i = 0
    try {
        var fo=FileWriter("test.txt")
        fo.write(i + " " + str + "\n")
        fo.close()
        i+1
    }catch (ex:Exception){
        println(ex.message)
    }
}

错误:(37, 20) Kotlin: 不能使用提供的参数调用以下函数:

public final operator fun plus(other: Byte): Int 定义在 kotlin.Int

public final operator fun plus(other: Double): Double 定义在 kotlin.Int

public final operator fun plus(other: Float): kotlin.Int 中定义的浮点数

public final operator fun plus(other: Int): Int 定义在 kotlin.Int

public final operator fun plus(other: Long): Long 定义在 kotlin.Int

public final operator fun plus(other: Short): Int 定义在 kotlin.Int

标签: kotlinrandom

解决方案


如评论中所述,readLines()结合使用random()

File("file.txt").readLines().random()

但是,正如文档readLines()所说:

请勿将此功能用于大文件。


推荐阅读