引言
本篇将介绍我最近在对
Android项目进行功能开发时,对文件操作的一些笔记分享。
在阅读本文前,你需要了解常用的 Android 文件存储方式:
- (1):保存到
 外部SD卡(由于现在的手机大部分不支持SD卡扩展,该方法的使用率也逐渐降低,通常用于对旧设备进行适配);- (2):保存到
 系统内部文件夹(如存储照片与音视频),该方法需要提前在Manifest清单文件中申请文件读写权限;- (3):保存到当前App的
 系统沙盒中(较为常见);- (4):保存到当前App的
 缓存文件夹中;- (5):在开发过程中,
 将需要的文件存放到assets或resource文件夹中,并集成到App安装包(若保存至assets文件夹,则通常需要先将其复制到手机内存中)
assets 文件操作
拷贝 assets文件夹 到内部存储
// Copy Dir from Assets to Phone
fun copyAssetsDirToPhone(context: Context, localAssetsPath: String) {
    var filePath = localAssetsPath
    try {
        val fileList = context.assets.list(filePath)!!
        if (fileList.isNotEmpty()) {
            val file = context.filesDir.absolutePath + File.separator + filePath
            // Create new folder before first copy
            file.mkdirs()
            for (fileName in fileList) {
                filePath = filePath + File.separator + fileName
                copyAssetsDirToPhone(context, filePath)
                filePath = filePath.substring(0, filePath.lastIndexOf(File.separator))
            }
        } else {
            // Current selected assets is a file
            val inputStream: InputStream = context.assets.open(filePath)
            val file = context.filesDir.absolutePath + File.separator + filePath
            if (!file.exists() || file.length() == 0L) {
                val fileOutputStream = FileOutputStream(file)
                var len: Int
                val buffer = ByteArray(1024)
                while (inputStream.read(buffer).also { len = it } != -1) {
                    fileOutputStream.write(buffer, 0, len)
                }
                fileOutputStream.flush()
                inputStream.close()
                fileOutputStream.close()
            }
        }
    } catch (exception: Exception) {
        exception.printStackTrace()
    }
}
拷贝 assets文件 到内部存储
// Copy file from Assets to Phone
fun copyAssetsFileToPhone(context: Context, fileName: String) {
    try {
        val inputStream: InputStream = context.assets.open(fileName)
        val file = File(context.filesDir.absolutePath + File.separator + fileName)
        if (!file.exists() || file.length() == 0L) {
            // if file not exist, FileOutputStream will auto create it
            val fileOutputStream = FileOutputStream(file)
            var len: Int
            val buffer = ByteArray(1024)
            while (inputStream.read(buffer).also { len = it } != -1) {
                fileOutputStream.write(buffer, 0, len)
            }
            fileOutputStream.flush()
            inputStream.close()
            fileOutputStream.close()
        }
    } catch (exception: Exception) {
        exception.printStackTrace()
    }
}