在 Groovy 中解压 zip 二进制文件

问题描述 投票:0回答:1

我有一个字符串变量,其中包含 zip 文件的二进制文件。我想解压缩它,而不将该 zip 文件保存在计算机上,只保存 zip 文件中包含的文件。我可以使用哪些库和方法来实现此目的。
我有这个库

import java.util.zip.ZipInputStream
import java.io.FileOutputStream

def zipFilePath = "ask me for the path "

但问题是我没有路。我只有二进制代码的变量。

groovy binary zip
1个回答
0
投票

我将对你的意思做出一些假设。当你保存时,你会得到一个包含二进制文件的

String
,而不仅仅是文本,它不起作用。您可以有一个可以解码为二进制(即 byte[])的 base64 编码的字符串,但您可以将原始二进制文件放在
String
中,并能够对其执行解压缩操作。我假设您的意思是它是 base64 编码的,我将编写一个例程来解码它,并对其执行解压缩。

我想解压它而不将该zip文件保存在计算机上并仅保存zip文件中包含的文件

当您保存时,我假设您的意思是解压缩二进制文件中包含的内容

byte[]
,但您可以将 zip 中包含的每个文件保存到磁盘上的目录中。如果您有意的话,我将指出如何不将文件保存到磁盘。

言归正传:

void unzipBase64(String base64EncodedZip, File directory) {
    new ZipInputStream( new ByteArrayInputStream( base64EncodedZip.base64Decode() )).withCloseable { ZipInputStream stream ->
       while( (ZipEntry entry = stream.nextEntry) != null ) {
           if( !entry.isDirectory() ) {
              File out = new File( directory, entry.name )
              out.mkdirs()
              out.withOutputStream { os ->
                 os << stream
              }
           }
       }
    }
}

如果您想将其全部读入内存(请小心,因为它是压缩启动的并且可能会增加内存使用量)。您只需将

FileOutputStream
替换为
ByteOutputStream
并返回
Map<String,ByteArrayInputStream>

Map<String,InputStream> unzipBase64(String base64EncodedZip, File directory) {
     Map<String,InputStream> result = [:]
    new ZipInputStream( new ByteArrayInputStream( base64EncodedZip.base64Decode() )).withCloseable { ZipInputStream stream ->
       while( (ZipEntry entry = stream.nextEntry) != null ) {
           if( !entry.isDirectory() ) {
              ByteArrayOutputStream out = new ByteArrayOutputStream(entry.size)
              out.withCloseable { os ->
                 os << stream
              }
              result[entry.name] = new ByteArrayInputStream( out.toByteArray() )
           }
       }
    }
    return result
}
© www.soinside.com 2019 - 2024. All rights reserved.