Android Intent Import And Read File

April 20, 2018
Intent.ACTION_GET_CONTENT

Use Intent.ACTION_GET_CONTENT to import or read file.

val intent = Intent(Intent.ACTION_GET_CONTENT)
// intent.type = "file/*"
intent.type = "application/octet-stream"
activity.startActivityForResult(intent, FILE_REQUEST_CODE)

Edit AndroidManifest.xml to allow reading of open/import file.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>

Override Activity.onActivityResult to handle the file request.

Use [ContentResolver.openInputStream] to read input stream / the file.

class BackupActivity : AppCompatActivity() {
    companion object {
        private const val FILE_REQUEST_CODE = 1
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == FILE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val uri = data?.data
                if (uri != null) {
                    val inputStream = contentResolver.openInputStream(uri)
                    
                    // copy input stream to file
                    val outputFile = File(context.cacheDir, "output.txt")
                    val outputStream = FileOutputStream(outputFile)
                    inputStream.use { input ->
                        outputStream.use { output ->
                            input.copyTo(output)
                        }
                    }

                    // copy input stream to bytearray/string
                    /*
                    val outputStream = ByteArrayOutputStream()
                    inputStream.use { input ->
                        outputStream.use { output ->
                            input.copyTo(output)
                        }
                    }
                    val byteArray = outputStream.toByteArray()
                    val outputString = String(byteArray, Charsets.UTF_8)
                     */
                }
                else {
                    Toast.makeText(this, "No Data", Toast.LENGTH_LONG).show()
                }
            }
            else {
                Toast.makeText(this, "No Result", Toast.LENGTH_LONG).show()
            }
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.