java - 对文件进行Base64编码并压缩

标签 java encoding base64 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();
    }
}

最佳答案

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/

相关文章:

法语字符的 HTML 编码

eclipse - 在 Apache Tomcat 上运行 jsp 网页的编码问题

c# - 解码 Base64/Quoted Printable 编码的 UTF8 字符串

javascript - 根据 base 64 内容确定图像类型

java - 转换为 Set 时 List 的大小会发生变化

java - "Constructor cannot be applied to given types"错误

java - org.xml.sax.SAXParseException;找不到元素'beans :beans 的声明

java - Eclipse 在 Mac 上显示 � 字符而不是 §

php - parse_signed_request - base64_url_decode - strstr 使用

java - 如何使用 Gson 从 JSON 一次读取一个变量?