首页 文章

将base64解码后的字符串保存到zip文件中

提问于
浏览
0

我想使用上面提到的代码将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中运行代码 . 当我尝试打开zip时,它表示打开文件时出错 .

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

压缩文件是否未在rhel6中正确保存,或者是否需要进行任何代码修改?

2 回答

  • 0

    不要从字节数组( 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);
    }
    

    实际上,由于新的 try-with-resources 语句,上面需要java 1.7 .

    对于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();
        }
    }
    
  • 0

    那不行 . 您正在写入普通文件而不打包内容 . 将java zip库与 ZipOutputStreamZipEntry 等一起使用 .

相关问题