Android registerForActivityResult返回的Uri转File,由于比较难找,特此记录一下。
思路:通过Uri获取文件名,通过Uri获取数据流,再创建文件。
1.
val fileUri = result.data!!.data!!
val cursor = requireContext().contentResolver.query(fileUri, null, null, null, null, null)
cursor?.let {
it.moveToFirst()
val fileName = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
val fileSize = it.getString(it.getColumnIndex(OpenableColumns.SIZE)).toInt()/1024
cursor.close()
}
2.通过Uri获取数据流
@Throws(IOException::class)
fun readTextFromUri(uri: Uri,contentResolver: ContentResolver): InputStream {
val openInputStream = contentResolver.openInputStream(uri)
return openInputStream!!
}
3.数据流写入文件
@Throws(IOException::class)
fun copyInputStreamToFile(inputStream: InputStream, file: File) {
FileOutputStream(file).use { outputStream ->
var read: Int
val bytes = ByteArray(1024)
while (inputStream.read(bytes).also { read = it } != -1) {
outputStream.write(bytes, 0, read)
}
}
}