How to read and write txt files in android in kotlin

后端 未结 5 1059
小鲜肉
小鲜肉 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:11

    You need to use internal or external storage directory for your file.

    Internal:

    val path = context.getFilesDir()
    

    External:

    val path = context.getExternalFilesDir(null)
    

    If you want to use external storage you'll need to add a permission to the manifest:

    
    

    Create your directory:

    val letDirectory = File(path, "LET")
    letDirectory.mkdirs()
    

    Then create your file:

    val file = File(letDirectory, "Records.txt")
    

    Then you can write to it:

    FileOutputStream(file).use {
        it.write("record goes here".getBytes())
    }
    

    or just

    file.appendText("record goes here")
    

    And read:

    val inputAsString = FileInputStream(file).bufferedReader().use { it.readText() }
    

提交回复
热议问题