使用 Scala 进行 Gzip 压缩导致不是存档错误

Gzip Compression with Scala resulting in not an archive error

我正在对文档进行更改,然后我需要使用 gzip 压缩文档,加密并保存。

每个单独的代码块都按预期通过了单元测试,但它们一起失败了,当我打开文件时收到一条错误消息,提示它不是存档。

基本代码如下,非常感谢任何帮助,提前致谢!

val zipped = compressFile1(replaced)

def compressFile1(fileContents: String): Array[Byte] = {
  val bos = new ByteArrayOutputStream()
  val gzs = new GZIPOutputStream(bos)
  gzs.write(fileContents.getBytes("UTF-8"))
  gzs.close()
  val compressed = bos.toByteArray
  bos.close()
  compressed
}

然后我加密文件

val encrypted = encrypt(zipped.toString)

def encrypt(value: String): String = {
  val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
  cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(encryptionPassword))
  Base64.encodeBase64String(cipher.doFinal(value.getBytes("UTF-8")))
}

然后保存

val file = writeStringToFile(new File("testfile1.gz"), encrypted)

再次感谢您

Array[Byte] 上调用 .toString 实际上返回类似 [B@4d2f7117 的内容(标准 toString 实现)。它没有做你期望的事情,这是......

val encrypted = encrypt(new String(zipped))

而不是

val encrypted = encrypt(zipped.toString)