【Kotlin】inputStreamをファイルに出力

kotlinをはじめて数日しかたっていないKotlin初心者です

間違っていたり効率悪かったり、文法がおかしかったりする可能性が大きいのでご注意ください

デバイス内の画像をアプリ内にファイルとして保存

下記URLをコピペして画像をImageViewに表示できるように

https://github.com/orimomo/picture-frame-app/tree/master

以下の部分に少し追記

data?.data?.also { uri ->
    Log.d("VIDEOURI", "URI:${uri}")
    val inputStream = contentResolver?.openInputStream(uri)
    val image = BitmapFactory.decodeStream(inputStream)
    val imageView = findViewById<ImageView>(R.id.imageView)
    imageView.setImageBitmap(image)

    //追記部分
    //アプリ内にファイル書き込み
    val path = applicationContext.filesDir
    val context = this.applicationContext
    val fileName = uriToFileName(context, uri)
    val filePath = path.toString() + "/" + fileName
    inputStream?.toFile(filePath)
    //追記終了
}

以下の関数を追加

fun InputStream.toFile(path: String) {
    File(path).outputStream().use {
        this.copyTo(it)
    }
}

fun uriToFileName(context: Context, uri: Uri): String? {
    return when (uri.scheme) {
    ContentResolver.SCHEME_FILE -> {
        File(uri.path).name
    }
    ContentResolver.SCHEME_CONTENT -> {
        val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME)
        val cursor = context.contentResolver.query(uri, projection, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) { it.getString(0) } else null
            }
        }
        else -> null
    }
}

以上でアプリ内に選択した画像が保存される

シミュレーターの場合は「/data/data/パッケージ名/files」以下に保存される

ファイル名の重複等はチェックしていない

参考URL

https://qiita.com/orimomo/items/4b741dc252bc261a8469

https://github.com/orimomo/picture-frame-app/tree/master

https://teratail.com/questions/117206

https://stackoverflow.com/questions/35528409/write-a-large-inputstream-to-file-in-kotlin/35529070