How to read and write txt files in android in kotlin

后端 未结 5 1054
小鲜肉
小鲜肉 2021-02-05 22:17

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 f

5条回答
  •  情书的邮戳
    2021-02-05 23:20

    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.

    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.

提交回复
热议问题