如何在Kotlin中的android中读写txt文件 [英] How to read and write txt files in android in kotlin

查看:651
本文介绍了如何在Kotlin中的android中读写txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是kotlin和android studio的初学者. 我可以访问大多数android小部件,但无法访问文件,到目前为止,我仅遇到了以下无效的代码.该应用程序崩溃了...

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的答案.使用文件时,可能无法保证您对所需文件操作的100%成功.因此,最好尝试捕获诸如filenotfoundexception之类的异常,并适当注意程序控制的流程.

I just want to add on to TpoM6oH's answer. When working with Files, you may be not guaranteed with 100% success on the file operations you intend. So, it is a better practice to try and catch for exceptions like filenotfoundexception etc. and take a due care about the flow of program control.

要在 Android 的外部存储中创建文件,您可以使用

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

Environment.getExternalStorageDirectory()

,然后检查该位置是否存在.如果没有,请创建一个文件,然后继续使用 Kotlin

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
}

希望这会有所帮助.

这篇关于如何在Kotlin中的android中读写txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆