LoginSignup
5
3

More than 5 years have passed since last update.

Kotlinでアセットファイルを外部ストレージにコピーする

Posted at

kotlinで、Androidアプリの assets フォルダにあるファイルを外部ストレージ にコピーする方法です。

方法


//コピー先フォルダのパス
private val basePath = Environment.getExternalStorageDirectory().path + File.separator + "hoge"

/**
 * アセットにあるファイルをストレージにコピーします
 * @param context Context
 * @param assetName コピーするアセットの名前
 */
fun copyAssetToExternalStorage(context: Context, assetName: String){

    //上記フォルダパスにアセット名を含めたフルパス
    val fullPath = basePath + File.separator + assetName

    val dir = File(basePath)

    if(!dir.exists()){
        if(!dir.mkdirs()){
            return
        }
    }

    context.assets.open(assetName).use { inputStream ->
        FileOutputStream(File(fullPath), false).use { outputStream ->
            inputStream.copyTo(outputStream)
        }
    }
}

参考にさせていただいたサイト

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3