I'm still pretty much a beginner in kotlin and android studio. I can access most of the android widgets but I cannot access files and so far I managed to come across only the following code which does not work. The app crashes...

var recordsFile = File("/LET/Records.txt")
recordsFile.appendText("record goes here")

It will be much appreciated if I can also know how to create the file at a specific location. Like at root directory or internal storage or in a file in the internal storage. Thanks..

推荐答案

我只想补充一下TpoM6oH的答案.使用文件时,可能不能保证百分之百成功完成您想要的文件操作.因此,更好的做法是try 并捕获诸如filenotfordexception等异常,并适当注意程序控制流.

To create a file at the external storage in Android, you can get the location using

Environment.getExternalStorageDirectory()

and check if the location exists. If it does not, create one and continue creating and writing your file using Kotlin

val sd_main = File(Environment.getExternalStorageDirectory()+"/yourlocation")
var success = true
if (!sd_main.exists())
    success = sd_main.mkdir()

if (success) {
    val sd = File("filename.txt")

    if (!sd.exists())
        success = sd.mkdir()

    if (success) {
        // directory exists or already created
        val dest = File(sd, file_name)
        try {
            // response is the data written to file
            PrintWriter(dest).use { out -> out.println(response) }
        } catch (e: Exception) {
            // handle the exception
        }
    }
} else {
    // directory creation is not successful
}

Hope this helps.

Kotlin相关问答推荐

使用数据存储首选项Kotlin Jetpack Compose

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

关键字';在When Kotlin When-语句中

如何修改muableStateMapOf的值?

用Quarkus和Reactor重写异步过滤器中的数据流

如何检测一个值是否是Kotlin中的枚举实例?

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

在 Compose 中使用 Text() 时如何获取文本的大小?

Jetpack Compose:当状态从另一个活动改变时强制重组

从 Kotlin 调用 Java 时可以为空的规则是什么

kotlin-bom 库是做什么的?

Kapt不适用于Android Studio 3.0中的AutoValue

用Gradle Kotlin DSL构建源jar?

从命令行运行Java到Kotlin转换器?

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

Kotlin中保留的关键字是什么?

如何在Kotlin中使用Handler和handleMessage?

在多平台子元素中使用kapt

var str:String是可变的还是不可变的?

Dagger 2 androidx fragment不兼容类型