Groovy:将Zip内容字节转换为字符串

zbq4xfa0  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(76)

我有这两个类:

  1. Message class
  2. MessageLog class
    第一个类Message有一个方法getBody,它可以返回一个我们可以指定的对象(如文档中所示),第二个类MessageLog有一个方法addAttachmentAsString,它将第二个参数作为String作为附件的内容。
    现在,我在Message.body中有一个Zip内容,我可以使用getBody方法来获取字节内容,然后我想传递给第二个类的方法,即MessageLog.addAttachmentAsString。内容将被传递给第二个参数,它只接受String。
    我尝试了以下代码:
messageLog.addAttachmentAsString("attachment_name", message.getBody(String), "application/zip")

字符串
但结果是,我可以下载附件,但zip内容已损坏,无法打开。
有没有可能转换压缩内容,这是在字节和字符串传递而不破坏内容?谢谢。

5m1hhzi4

5m1hhzi41#

所以Zip文件是二进制的。字符串是使用字符编码格式(ASCII,UTF-8,UTF-24等)可读的二进制数据的解释。不是所有的二进制都是字符串,但所有的字符串都是二进制的。Zip文件不是不能解释为字符串,因为它们不遵循任何字符编码的规则。
但是,有一种方法可以使用Base64编码将二进制数据表示为文本。因此,如果您对zip文件附件进行Base64编码,那么您可以将其作为String返回,但是为了解压缩文件,您需要首先解码Base64以在解压缩之前返回二进制。
从你的帖子中,你没有提到任何关于电子邮件或base64编码的事情,所以很难知道这是什么绊倒了你,还是谁实现了这个方法没有使用base64,它只是乱码。
如果不将base64文件解码回底层的二进制文件,则无法读取该文件。下面是一个使用Base64进行编码和解码的示例:

import java.util.zip.*
// create a zip file with one text file inside it.
File zip = new File("output.zip")
zip.withOutputStream { out ->
   ZipOutputStream zos = new ZipOutputStream( out )
   zos.putNextEntry( new ZipEntry("output.txt"))
   zos.write("'ello potato cakes!  This is a string we're going to write to the zip file.".getBytes("UTF-8"))
   zos.closeEntry()
   zos.flush()
   zos.close()
}

// Base64 encode the zip file
String base64Zip = zip.bytes.encodeBase64().toString()

println("Encoded zip as base64")
println( base64Zip )

println("Decoding base64")

// read the zip file by first base64 decoding it, and reading it as a ZipInputStream.
new ZipInputStream( new ByteArrayInputStream( base64Zip.decodeBase64() ) ).withStream { zin ->
   ZipEntry entry = null
   while( (entry = zin.nextEntry) != null ) {
      println( entry.name )
      ByteArrayOutputStream baos = new ByteArrayOutputStream()
      baos << zin
      println( baos.toString("UTF-8") )
   }
}

字符串

相关问题