将 base64 解码后的字符串保存到 zip 文件中
saving base64 decoded string into a zip file
我正在尝试使用上述代码将 base64 解码字符串保存到 zip 文件中:
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/home/wemohamm/Desktop/test.zip")));
out.write(decodedString);
out.close();
这里decodedString
包含base64解码后的字符串,我可以输出。
我是 运行 rhel6 中的代码 Java 1.6。当我尝试打开 zip 时,它说打开文件时发生错误。
相同的代码如果我使用 Windows 7 Java 1.6 路径 c:\test\test.zip
工作正常。
zip 是否没有在 rhel6 中正确保存,或者我是否需要做任何代码修改?
那不行。您正在写入一个普通文件而不打包内容。将 java zip 库与 ZipOutputStream
、ZipEntry
等一起使用。
不要从字节数组 (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();
}
}
我正在尝试使用上述代码将 base64 解码字符串保存到 zip 文件中:
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/home/wemohamm/Desktop/test.zip")));
out.write(decodedString);
out.close();
这里decodedString
包含base64解码后的字符串,我可以输出。
我是 运行 rhel6 中的代码 Java 1.6。当我尝试打开 zip 时,它说打开文件时发生错误。
相同的代码如果我使用 Windows 7 Java 1.6 路径 c:\test\test.zip
工作正常。
zip 是否没有在 rhel6 中正确保存,或者我是否需要做任何代码修改?
那不行。您正在写入一个普通文件而不打包内容。将 java zip 库与 ZipOutputStream
、ZipEntry
等一起使用。
不要从字节数组 (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();
}
}