Records in .txt file [duplicated]

1

I'm trying to save some words contained in a variable text in a .txt file by clicking on a button . The drawback is that you should be saving a sequence of what you put in the variable text , but only save what you put it in the last execution.

var texto ="Registro 1"
        btnInt.setOnClickListener(){
            try {
                val archivo = OutputStreamWriter(openFileOutput("notas.txt", Activity.MODE_PRIVATE))

                archivo.write(texto)

                archivo.flush()
                archivo.close()

            } catch (e: Exception) {
                Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show()
            }
        }

If the text value changes in the next execution (var text="Record 2"), the expected result is that

appears in the "notes.txt" file.

Record 1

Record 2

But, I reiterate, at this moment the value that is being expressed is that of the last execution

Record 2

    
asked by saheco 13.03.2018 в 16:22
source

1 answer

1

You should check how to create a file and save text inside the file in Kotlin:

Save string in a txt file

In this case if you want to create a file and add information you can use the method appendText ()

var counter = 1;

fun writeToFile() {
    //Define ruta en almacenamiento externo y si deseas un directorio.
    val path = File(Environment.getExternalStorageDirectory(),"/misarchivos/")
    var success = true
    //Si el path no existe, trata de crear el directorio.
    if (!path.exists()) {
        success = path.mkdir()
    }

    //Si el path existe o creo directorio sin problemas ahora crea archivo.
    if (success) {
         val text = "Prueba texto "  + counter++ + "\n"
        //Escribe texto en archivo.
        File(path,"output.txt").appendText(text)
    }
}

This way when calling the method you can add text to it, example:

Prueba texto 1
Prueba texto 2
Prueba texto 3
Prueba texto 4
Prueba texto 5
Prueba texto 6
Prueba texto 7
Prueba texto 8
Prueba texto 9
Prueba texto 10
Prueba texto 11
    
answered by 13.03.2018 в 17:57