Base64的编码(Encode)与解码(Decode),及记录JDK10下部分使用 new BASE64Decoder().encode(byte[] bytes)方法报错

本文介绍Base64的编码和解码过程,并记录在JDK10环境下使用`new BASE64Decoder().encode(byte[] bytes)`方法出现的错误。文章提到了Java 8的Base64性能优于sun.misc套件,且在JDK10中sun.misc包已被移除,提醒开发者注意代码兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:https://magiclen.org/java-base64/

https://blog.youkuaiyun.com/zhou_kapenter/article/details/62890262

本文记录Base64的编码(Encode)与解码(Decode),及记录JDK10下部分使用 new BASE64Decoder().encode(byte[] bytes)方法报错。

目前有三种方式进行base64的编解码。

说明: 在Java用Base64一点都不难,不用几行程式码就解决了!只是这个sun.misc套件所提供的Base64功能,编码和解码的效率并不太好--->
(1)在java早期使用JDK里sun.misc套件下的BASE64Encoder和BASE64Decoder这两个类别,主要代码如下
final BASE64Encoder encoder = new BASE64Encoder();
final BASE64Decoder decoder = new BASE64Decoder();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = encoder.encode(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));

(2)appache--Apache Commons Codec有提供Base64的编码与解码功能,会使用到org.apache.commons.codec.binary套件下的Base64类别,使用方法如下:
final Base64 base64 = new Base64();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = base64.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(base64.decode(encodedText), "UTF-8"));
使用方法无区别,就是包和sun.misc套件包名有区别,效能实际执行起来也快了不少。

Java 8之后的作法(注意版本)
Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下
final Base64.Decoder decoder = Base64.getDecoder();
final Base64.Encoder encoder = Base64.getEncoder();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = encoder.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decode(encodedText), "UTF-8"));

性能对比:Java 8提供的Base64,要比sun.mis c套件提供的还要快至少11倍,比Apache Commons Codec提供的还要快至少3倍。

特别说明:本菜之前切换jdk10之后,项目中用到的sun.misc套件提供的base64编解码方式已经被删除,希望朋友们以后注意。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值