Android. Save file into shared directory on device

Viewed 2399

I can save some data into file

    val byteArrayOutputStream = ByteArrayOutputStream()
    byteArrayOutputStream.writeTo(openFileOutput("FILENAME", Context.MODE_PRIVATE))
    val data = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    byteArrayOutputStream.write(data)
    byteArrayOutputStream.close()

But I want to save it not into my app directory, but into some shared folder.

2 Answers

Solved!

val file = File(Environment.getExternalStorageDirectory(), "myfile.txt")
FileOutputStream(file).use {
  it.write("ASDFGHJKL".toByteArray())
}

U have also to ask run time permission

if (PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE)) {
  ActivityCompat.requestPermissions(this, arrayOf(WRITE_EXTERNAL_STORAGE), 1)
} else {
  createFile()
}

...

 override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 1) {
            if (grantResults[0] == PERMISSION_GRANTED) {
                createFile()
            } else {
                // разрешение не получено
            }
        }
    }

If you want to access External Storage then Try this android.os.Environment.getExternalStorageDirectory()

Related