You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin开发Android随机读文本行应用崩溃求助

Android应用点击按钮崩溃:文本文件读取问题解决

崩溃原因分析

从崩溃日志的核心报错可直接定位问题:

Caused by: java.nio.file.NoSuchFileException: chal.txt

这说明应用在当前路径下找不到chal.txt文件——Android应用的文件系统沙箱机制不允许直接访问根路径文件,普通Java文件读取API也不适用于读取应用内置资源文件,你原代码的文件读取方式完全错误。

解决步骤

1. 正确放置文本文件

  • 在项目src/main目录右键选择 New → Folder → Assets Folder,创建assets目录(已存在则跳过)。
  • 将chal.txt复制到assets目录下。

2. 修改代码读取assets文件

替换原文件读取逻辑,使用Android原生AssetManager读取资源,同时修复随机数越界问题:

package com.example.exampleapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rollButton = findViewById<Button>(R.id.rollButton)
        val resultsTextView = findViewById<TextView>(R.id.textView)

        // 提前读取文件内容,避免重复IO操作
        val allLines = try {
            assets.open("chal.txt").bufferedReader().readLines()
        } catch (e: Exception) {
            listOf("读取文件失败: ${e.message}")
        }

        rollButton.setOnClickListener {
            if (allLines.isEmpty()) {
                resultsTextView.text = "无可用内容"
                return@setOnClickListener
            }
            // 生成安全的随机索引,避免数组越界
            val randomIndex = Random.nextInt(allLines.size)
            resultsTextView.text = allLines[randomIndex]
        }
    }
}

3. 代码修改说明

  • 移除@RequiresApi(Build.VERSION_CODES.O)注解,应用可兼容更低版本Android,无需强制API 26。
  • 用assets.open("chal.txt")读取内置资源,这是Android读取本地资源的标准方式。
  • 提前在onCreate读取文件内容,避免每次点击重复IO操作,提升性能。
  • 增加异常捕获,文件读取失败也不会崩溃。
  • 随机数基于文件实际行数生成,彻底避免数组越界风险。

崩溃日志快速解读技巧

下次遇到崩溃日志,直接看最内层的Caused by条目,这就是崩溃的根本原因,无需关注外层嵌套的反射调用异常。

内容的提问来源于stack exchange,提问作者Ramen187

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:05:15