简体   繁体   English

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

[英]saving base64 decoded string into a zip file

I am trying to save a base64 decoded string into a zip file using the mentioned code: 我正在尝试使用上述代码将base64解码的字符串保存到zip文件中:

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

Here decodedString contains base64 decoded string and I can output it. 在这里, decodedString包含base64解码的字符串,我可以输出它。 I am running the code in rhel6 with Java 1.6. 我正在用Java 1.6在rhel6中运行代码。 When I try to open the zip, it says error occurred while opening file. 当我尝试打开zip时,它说打开文件时发生错误。

The same code if I use with Windows 7 Java 1.6 with path c:\\\\test\\test.zip is working fine. 如果我将Windows 7 Java 1.6与路径c:\\\\test\\test.zip一起使用,则可以使用相同的代码。

Is the zip not getting saved correctly in rhel6 or if there is any code modifications I need to do? zip是否没有正确保存在rhel6中,或者是否需要做任何代码修改?

That won't work. 那行不通。 You are writing to a ordinary file without packing the content. 您正在写入普通文件而不打包内容。 Use the java zip library with ZipOutputStream , ZipEntry and so on. 将Java zip库与ZipOutputStreamZipEntry等配合使用。

Don't create a string from your byte array ( String decodedString = new String(byteArray); ), to then use an OutputStreamWriter to write the string, because then you are running the risk of introducing encoding issues that are platform dependent. 不要从字节数组中创建一个字符串( String decodedString = new String(byteArray); ),然后使用OutputStreamWriter编写该字符串,因为这样会带来引入与平台相关的编码问题的风险。

Just use FileOutputStream to write out the byte array ( byte[] byteArray ) directly to file. 只需使用FileOutputStream将字节数组( byte[] byteArray )直接byte[] byteArray文件中即可。

Something like: 就像是:

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

Actually, the above requires java 1.7+, because of the new try-with-resources statement. 实际上,由于新的try-with-resources语句,上述内容需要Java 1.7+。

For Java 1.6, you can do this: 对于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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM