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

Kotlin自定义类写入CSV文件遇空指针等异常问题求助

问题分析与解决

错误原因

你把工具类写成继承AppCompatActivity的类,但这个类并没有被Android系统作为Activity实例化——没有经过onCreate等生命周期流程,内部的Context对象是null的,调用openFileOutput自然会触发空指针异常。而且工具类继承Activity本身就是错误的设计,完全没必要。

修复方案

把DryTest改成普通工具类,通过方法参数或者构造函数传入有效的Context,用这个Context来操作文件。下面是修正后的代码:

修正后的工具类代码

package com.example.jobndays

import android.content.Context
import java.io.FileOutputStream

class DryTest {

    // 写入字符串到私有文件
    fun writeToFile(context: Context, fileName: String, content: String) {
        context.openFileOutput(fileName, Context.MODE_PRIVATE).use { outputStream ->
            outputStream.write(content.toByteArray())
        }
    }

    // 扩展:写入类对象到CSV文件的示例(假设你有一个Bobbin数据类)
    fun writeBobbinListToCsv(context: Context, fileName: String, bobbinList: List<Bobbin>) {
        val csvContent = buildString {
            // 写入CSV表头
            append("ID,Name,Quantity\n")
            // 写入每一行数据
            bobbinList.forEach { bobbin ->
                append("${bobbin.id},${bobbin.name},${bobbin.quantity}\n")
            }
        }
        writeToFile(context, fileName, csvContent)
    }
}

// 示例数据类
data class Bobbin(val id: Int, val name: String, val quantity: Int)

在Activity中调用工具类

// 在你的主Activity里
val dryTest = DryTest()
// 写入简单字符串
dryTest.writeToFile(this, "bobbin.csv", "fella")

// 写入对象列表到CSV
val bobbinList = listOf(
    Bobbin(1, "BobbinA", 100),
    Bobbin(2, "BobbinB", 200)
)
dryTest.writeBobbinListToCsv(this, "bobbin_data.csv", bobbinList)

注意事项

  • 传入的Context尽量用Application的Context(applicationContext)避免内存泄漏,尤其是工具类可能长期持有Context的情况下。
  • 使用use函数自动关闭流,不用手动处理close(),更安全简洁。
  • 如果要写入外部存储,需要遵循Android版本对应的存储规则(Android 10及以上用Scoped Storage,无需申请传统的读写外部存储权限)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:05:44