-
-
Save rocka/847df66cca3481c4072d6c65011801d6 to your computer and use it in GitHub Desktop.
Function to recursively copy files from an Android asset directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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