Skip to content

Instantly share code, notes, and snippets.

@rocka
Forked from tylerchesley/gist:6198074
Last active March 11, 2021 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocka/847df66cca3481c4072d6c65011801d6 to your computer and use it in GitHub Desktop.
Save rocka/847df66cca3481c4072d6c65011801d6 to your computer and use it in GitHub Desktop.
Function to recursively copy files from an Android asset directory
private fun copyFileOrDir(path: String) {
val assetManager = this.assets
try {
val assets = assetManager.list(path)
if (assets!!.isEmpty()) {
copyFile(path)
} else {
val dir = File("${applicationInfo.dataDir}/${path}")
if (!dir.exists()) dir.mkdir()
for (i in assets.indices) {
copyFileOrDir("${path}/${assets[i]}")
}
}
} catch (ex: IOException) {
Log.e("CopyFile", "I/O Exception", ex)
}
}
private fun copyFile(filename: String) {
val assetManager = this.assets
try {
val source = assetManager.open(filename)
val target = FileOutputStream("${applicationInfo.dataDir}/${filename}")
val buffer = ByteArray(1024)
var read: Int
while (source.read(buffer).also { read = it } != -1) {
target.write(buffer, 0, read)
}
source.close()
target.flush()
target.close()
} catch (e: Exception) {
Log.e("CopyFile", e.message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment