【问题标题】:saving base64 decoded string into a zip file将 base64 解码的字符串保存到 zip 文件中
【发布时间】:2015-06-16 13:11:05
【问题描述】:

我正在尝试使用上述代码将 base64 解码字符串保存到 zip 文件中:

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/home/wemohamm/Desktop/test.zip")));
out.write(decodedString);
out.close();

这里decodedString 包含base64 解码的字符串,我可以输出它。 我正在使用 Java 1.6 在 rhel6 中运行代码。当我尝试打开压缩包时,它说打开文件时出错。

如果我使用带有路径c:\\test\test.zip 的 Windows 7 Java 1.6 相同的代码工作正常。

zip 是否没有正确保存在 rhel6 中,或者我需要进行任何代码修改?

【问题讨论】:

  • 为什么不使用 ZipEntry 用 java 创建一个正确的 zip 文件?
  • decodedString 对象实际上是一个base64解码的字符串。而且我不知道如何将其保存为 zip。顺便说一句,上面的在windows下运行良好。如果有问题或需要修改,请分享
  • 您不创建 zip 存档,而是创建文件并将其命名为 .zip 使用@Andrew 的链接。
  • 其实这里decodedSting是一个zip文件流。为什么要压缩已经压缩的流。

标签: java string zip base64 decode


【解决方案1】:

不要从您的字节数组 (String decodedString = new String(byteArray);) 创建字符串,然后使用 OutputStreamWriter 写入字符串,因为这样您就有引入与平台相关的编码问题的风险。

只需使用FileOutputStream 将字节数组(byte[] byteArray)直接写入文件即可。

类似:

try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("/home/wemohamm/Desktop/test.zip"), 4096)) {
    out.write(byteArray);
}

其实上面需要java 1.7+,因为新的try-with-resources声明。

对于 Java 1.6,您可以这样做:

BufferedOutputStream out = null;
try {
    out = new BufferedOutputStream(new FileOutputStream("/home/wemohamm/Desktop/test.zip"), 4096);
    out.write(byteArray);
} finally {
    if (out != null) {
        out.close();
    }
}

【讨论】:

  • 我正在使用 jre 1.6,eclipse 指出错误并建议更改为 jre1.7,但我不能这样做,因为此代码要在 jre 1.6 上运行
【解决方案2】:

那是行不通的。您正在写入一个普通文件而不打包内容。使用带有ZipOutputStreamZipEntry 等的java zip 库。

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2016-12-03
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多