Zip file in assets

如何处理 assets 里的 zip 文件?

通常情况下 assets 里是不会出现 zip 文件的。但总有列外…

直接读取(不支持密码)

通过 JDK 自带的 ZipInputStream 进行直接读取。

val inputStream = assets.open("Hello.zip")
val zipInputStream = ZipInputStream(inputStream)
// 读取一个进入点
var zipEntry = zipInputStream.getNextEntry()
while (zipEntry != null) {
    val name = zipEntry.getName()
    val sb = StringBuffer("")
    val buffer = ByteArray(1024)
    var count = 0
    while (zipInputStream.read(buffer) > 0) {
        var str = String(buffer)
        str = str.trim { it <= ' ' }
        sb.append(str)
    }
    val value = sb.toString()
    // 定位到下一个文件入口
    toast("name: $name , value : value")
    zipEntry = zipInputStream.getNextEntry()
}
zipInputStream.close()

通过 zip4j 进行读取(支持密码,但需要 file 文件)

地址:http://www.lingala.net/zip4j.html

直接下载: http://central.maven.org/maven2/net/lingala/zip4j/zip4j/1.3.2/zip4j-1.3.2.jar

依赖:

compile group: 'net.lingala.zip4j', name: 'zip4j', version: '1.3.2'

implementation 'net.lingala.zip4j:zip4j:1.3.2'

虽然很久没有更新了,但依然可以用。毕竟 zip 也是很老的东西了。

看了下作者的博客,作者已经当爸了。难怪没有时间更新。。。

示例地址:https://github.com/dmp/zip4j/tree/master/src/net/lingala/zip4j/examples

//copy file to cache
val file = File(cacheDir.absolutePath + File.separator + "Hello.zip")
val outputStream = FileOutputStream(file)
IOUtils.copy(assets.open("Hello.zip"), outputStream);
// Initiate the ZipFile
val zipFile = ZipFile(file)
// If zip file is password protected then set the password
if (zipFile.isEncrypted) {
    zipFile.setPassword("123456")
}
//Get the FileHeader of the File you want to extract from the zip file. 
val fileHeader = zipFile.getFileHeader("Hello.txt")
if (fileHeader != null) {
    val inputStream = zipFile.getInputStream(fileHeader)
    val value = IOUtils.toString(inputStream, "UTF-8")
    log("name : ${fileHeader.fileName} , value $value")
    toast("name : ${fileHeader.fileName} , value $value")
}
//delete
file.delete()

上面的代码用到了 commons-io :

implementation 'commons-io:commons-io:2.6'
comments powered by Disqus