如何在 Kotlin 中从资产文件夹复制到外部或内部存储 Android Studio
How to copy in Kotlin from assets folder to external or internal storage Android Studio
我创建了几个代码,但都在 Java... 我尝试使用 ApplicationContext.assets 但什么都没有
有什么想法吗?
感谢和问候
此函数将从资产文件夹复制并保存在外部存储中:
fun copyAssets(context: Context) {
val assetManager: AssetManager = context.assets
var files: Array<String>? = null
try {
files = assetManager.list("")
if (files != null) for (filename in files) {
var `in`: InputStream? = null
var out: OutputStream? = null
try {
`in` = assetManager.open(filename)
val outFile = File(context.getExternalFilesDir(null), filename)
out = FileOutputStream(outFile)
copyFile(`in`, out)
} catch (e: IOException) {
Log.e("tag", "Failed to copy asset file: $filename", e)
} finally {
if (`in` != null) {
try {
`in`.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (out != null) {
try {
out.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
} catch (e: IOException) {
Log.e("tag", "Failed to get asset file list.", e)
}
}
@Throws(IOException::class)
private fun copyFile(`in`: InputStream?, out: OutputStream) {
val buffer = ByteArray(1024)
var read: Int? = null
while (`in`?.read(buffer).also({ read = it!! }) != -1) {
read?.let { out.write(buffer, 0, it) }
}
}
我创建了几个代码,但都在 Java... 我尝试使用 ApplicationContext.assets 但什么都没有
有什么想法吗?
感谢和问候
此函数将从资产文件夹复制并保存在外部存储中:
fun copyAssets(context: Context) {
val assetManager: AssetManager = context.assets
var files: Array<String>? = null
try {
files = assetManager.list("")
if (files != null) for (filename in files) {
var `in`: InputStream? = null
var out: OutputStream? = null
try {
`in` = assetManager.open(filename)
val outFile = File(context.getExternalFilesDir(null), filename)
out = FileOutputStream(outFile)
copyFile(`in`, out)
} catch (e: IOException) {
Log.e("tag", "Failed to copy asset file: $filename", e)
} finally {
if (`in` != null) {
try {
`in`.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (out != null) {
try {
out.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
} catch (e: IOException) {
Log.e("tag", "Failed to get asset file list.", e)
}
}
@Throws(IOException::class)
private fun copyFile(`in`: InputStream?, out: OutputStream) {
val buffer = ByteArray(1024)
var read: Int? = null
while (`in`?.read(buffer).also({ read = it!! }) != -1) {
read?.let { out.write(buffer, 0, it) }
}
}