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)
}
}