dmu*_*ali 5 java base64 encoding apache-commons-codec
我的目标是对文件进行编码并将其压缩到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();
}
}
Run Code Online (Sandbox Code Playgroud)
BASE64 编码数据通常比源数据长,但是您使用源数据的长度将编码写入输出流。
您可以使用生成的数组的大小而不是变量len。
buffer第二个注意事项 -每次编码字节时不要重新定义。只需将结果写入输出即可。
while ((len = in.read(buffer)) > 0) {
byte [] enc = Base64.encodeBase64(Arrays.copyOf(buffer, len));
out.write(enc, 0, enc.length);
}
Run Code Online (Sandbox Code Playgroud)
更新:使用Arrays.copyOf(...)设置编码输入缓冲区的长度。