FileHelper.kt 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.trust.ywx.utils
  2. import android.content.Context
  3. import android.util.Log
  4. import com.trust.ywx.AppManager
  5. import java.io.File
  6. import java.io.FileInputStream
  7. import java.io.FileOutputStream
  8. import java.io.IOException
  9. import java.util.zip.ZipEntry
  10. import java.util.zip.ZipInputStream
  11. class FileHelper {
  12. companion object {
  13. fun getDirPath(context: Context?, type: String?): String {
  14. return (context ?: AppManager.lastActivity())?.getExternalFilesDir(type)?.absolutePath!!
  15. }
  16. fun getFilePath(name: String, context: Context?, type: String?): String {
  17. val path = getDirPath(context, type) + File.separator + name
  18. return path
  19. }
  20. fun copyAssetFileToInternalStorage(
  21. context: Context,
  22. assetFileName: String,
  23. destFile: File
  24. ) {
  25. val assetManager = context.assets
  26. try {
  27. assetManager.open(assetFileName).use { `in` ->
  28. FileOutputStream(destFile).use { out ->
  29. val buffer = ByteArray(1024)
  30. var read: Int
  31. while ((`in`.read(buffer).also { read = it }) != -1) {
  32. out.write(buffer, 0, read)
  33. }
  34. Log.d(
  35. ">>>>>>>>>>>>>>CopyAssets",
  36. "Copied: " + assetFileName + " to " + destFile.getAbsolutePath()
  37. )
  38. }
  39. }
  40. } catch (e: IOException) {
  41. Log.e(">>>>>>>>>>>>>>CopyAssets", "Failed to copy asset: $assetFileName", e)
  42. }
  43. }
  44. @Throws(IOException::class)
  45. fun unzip(zipFile: File, targetDir: File) {
  46. if (!targetDir.exists()) targetDir.mkdirs()
  47. ZipInputStream(FileInputStream(zipFile)).use { zipIn ->
  48. var entry: ZipEntry?
  49. while ((zipIn.getNextEntry().also { entry = it }) != null) {
  50. val file = File(targetDir, entry!!.name)
  51. if (entry.isDirectory) {
  52. file.mkdirs()
  53. } else {
  54. // 确保父目录存在
  55. val parent = file.getParentFile()
  56. if (!parent.exists()) parent.mkdirs()
  57. FileOutputStream(file).use { fos ->
  58. val buffer = ByteArray(1024)
  59. var len: Int
  60. while ((zipIn.read(buffer).also { len = it }) > 0) {
  61. fos.write(buffer, 0, len)
  62. }
  63. }
  64. }
  65. zipIn.closeEntry()
  66. }
  67. }
  68. }
  69. }
  70. }