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.
如果你想访问外部存储,那么试试这个 android.os.Environment.getExternalStorageDirectory()
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 {
// разрешение не получено
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.