【发布时间】:2012-03-13 09:19:48
【问题描述】:
我的目标是对文件进行编码并将其压缩到 java 中的文件夹中。我必须使用 Apache 的 Commons-codec 库。我能够对其进行编码和压缩,并且工作正常,但是当我将其解码回其原始形式时,看起来该文件尚未完全编码。好像少了几个部分。谁能告诉我为什么会这样?
我还附上了我的代码部分供您参考,以便您可以相应地指导我。
private void zip() {
int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
try {
// Create the ZIP file
String outFilename = "H:\\OUTPUT.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
outFilename));
// Compress the files
for (int i : list.getSelectedIndices()) {
System.out.println(vector.elementAt(i));
FileInputStream in = new FileInputStream(vector.elementAt(i));
File f = vector.elementAt(i);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(f.getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buffer)) > 0) {
buffer = org.apache.commons.codec.binary.Base64
.encodeBase64(buffer);
out.write(buffer, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
System.out.println("caught exception");
e.printStackTrace();
}
}
【问题讨论】:
-
您能否提供一些示例,说明您投入了什么、得到了什么以及预期会得到什么?
-
我认为这与您的问题无关,但您的
in.read测试可能应该是in.read(buffer) > -1,因为这就是 api javadoc 所述。 javadoc 没有说0表示流结束。 docs.oracle.com/javase/1.4.2/docs/api/java/io/… -
如果我们的心是纯洁的,我们有生之年可以消灭base64。
-
我真的不明白为什么要对数据进行 base64 编码以放入 zip 文件中,但除此之外,您还有其他几个问题。你读取 len 个字节,base64 对它们进行编码(现在你有超过 len 个字节,然后你写 len 个字节,所以你的数据的最后一部分被跳过了。另外,当你的 sad 没有填满整个数组时(比如最后一个文件的一部分)你只想对实际字节进行编码,否则你会得到尾随的 0。
-
@dmurali 我说我不明白你为什么要费心对你的数据进行base64编码。毕竟,ZIP 压缩实际上是从一种 二进制 格式转换为另一种格式。编码没有添加任何东西,除了更多的字节和可能更差的压缩比。尝试不使用它。
标签: java encoding base64 apache-commons-codec