我的目标是用 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();
}
}
最佳答案
BASE64 编码数据通常比源数据长,但是您使用源数据的长度将编码数据写入输出流。
您使用了生成数组的大小,而不是您的变量 len
。
第二个注意 - 不要在每次编码一个字节时都重新定义 buffer
。只需将结果写入输出即可。
while ((len = in.read(buffer)) > 0) {
byte [] enc = Base64.encodeBase64(Arrays.copyOf(buffer, len));
out.write(enc, 0, enc.length);
}
更新:使用 Arrays.copyOf(...)设置编码输入缓冲区的长度。
关于java - 对文件进行Base64编码并压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681239/