Save string in a txt file

1

This is the code that I am implementing, I have also tried it in other ways, however in all the occasions that I execute it the application closes immediately

fun writeToFile() {
            val text = "Prueba texto"
            File("output.txt").writeText(text)
    }

Here I invoke it

if (isUpdate){Toast.makeText(contx,"Editado :)",Toast.LENGTH_LONG).show(); writeToFile() }
                        else{Toast.makeText(contx,"Error",Toast.LENGTH_LONG).show()}

error:

  

java.io.FileNotFoundException: output.txt (Read-only file system)

    
asked by saheco 08.03.2018 в 15:31
source

1 answer

-1

If you want to create it in this location you will not be able to do it only if your device has Root permissions:

File("output.txt").writeText(text)

I suggest you define a path in external storage, but before doing this it is important to define the permission in your file androidmanifest.xml

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and also define the manual request for permissions for WRITE_EXTERNAL_STORAGE , I add this example, add this method to get the answer when requesting permission:

  val REQUEST_PERMISSION = 1

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            REQUEST_PERMISSION -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("Jorgesys", "Se aceptaron permisos!")
            }
        }
    }

In the onCreate() method you define the request:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION)
        } else {
            Log.d("Jorgesys", "Se tienen permisos WRITE_EXTERNAL_STORAGE!")
        }
   ...
   ...
   ...

It is important to define the permission since otherwise you will not be able to create a directory or file, let alone write within it.

Create file and write within it in Kotlin

Now what you want is to create a file, and write within it, which can be done in this way:

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"
        //Escribe texto en archivo.
        File(path,"output.txt").writeText(text)
    }
}
    
answered by 08.03.2018 в 17:01