当前位置: 代码网 > it编程>编程语言>Java > Java Base64编码长度怎么计算?两种方式详解与实例

Java Base64编码长度怎么计算?两种方式详解与实例

2026年08月06日 Java 我要评论
看了太多计算的方式,也验证了下,这里个人总结一下,此处主要针对 java.util.base64 来总结一下:方式一base64.getmimeencoder().encode(readbuf)bas

看了太多计算的方式,也验证了下,这里个人总结一下,此处主要针对 java.util.base64 来总结一下:

方式一

base64.getmimeencoder().encode(readbuf)

base64类中源码方法如下:

    /**
     * returns a {@link encoder} that encodes using the
     * <a href="#mime" rel="external nofollow" >mime</a> type base64 encoding scheme.
     *
     * @return  a base64 encoder.
     */
    public static encoder getmimeencoder() {
        return encoder.rfc2045;
    }

使用此种方式encode则采用如下方式计算长度:

    private static final int mimelinemax = 76;
    private static final byte[] crlf = new byte[]{'\r', '\n'};

    /**
     * 根据原数据长度获取base64长度
     *
     * @param length
     * @return
     */
    public static long getbase64len(long length) {
        long len = 4 * ((length + 2) / 3);
        if (mimelinemax > 0)
            len += (len - 1) / mimelinemax * crlf.length;
        return len;
    }

方式二

base64.getencoder().encode(readbuf)

base64类中源码方法如下:

    /**
     * returns a {@link encoder} that encodes using the
     * <a href="#basic" rel="external nofollow" >basic</a> type base64 encoding scheme.
     *
     * @return  a base64 encoder.
     */
    public static encoder getencoder() {
         return encoder.rfc4648;
    }

使用此种方式encode则采用如下方式计算长度:

    public static long getbase64len(long length) {
        return (((4 * length / 3) + 3) & ~3);
    }

两种方式的区别在于编码后的格式稍微有差异,具体区别大家可以找个相同的文件采用不同的方式编码后看看编码内容;

以下为使用中的示例代码中:

    @override
    public void encodesavepos(inputstream is, string outpath, long pos) throws ioexception {
        randomaccessfile randomaccessfile = new randomaccessfile(outpath, "rw");
        randomaccessfile.seek(pos);
        byte[] buf = new byte[read_buffer_size];
        int readlen;
        byte[] readbuf;
        byte[] base64buf;
        bufferedinputstream bis = new bufferedinputstream(is);
        while (-1 != (readlen = bis.read(buf))) {
            readbuf = arrays.copyof(buf, readlen);
            base64buf = base64.getmimeencoder().encode(readbuf);
            randomaccessfile.write(base64buf, 0, base64buf.length);
        }
        bis.close();
        randomaccessfile.close();
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com