Java如何进行Base64的编码(Encode)与解码(Decode)?

Apache Commons Codec作法
Apache Commons Codec有提供Base64的编码与解码功能,会使用到org.apache.commons.codec.binary套件下的Base64类别,用法如下:

1
2
3
4
5
6
7
8
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套件还要更精简,效能实际执行起来也快了不少。缺点是需要引用Apache Commons Codec,很麻烦。

Java 8之后的作法
Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下:

1
2
3
4
5
6
7
8
9
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"));

  与sun.misc套件和Apache Commons Codec所提供的Base64编解码器来比较的话,Java 8提供的Base64拥有更好的效能。实际测试编码与解码速度的话,Java 8提供的Base64,要比sun.misc套件提供的还要快至少11倍,比Apache Commons Codec提供的还要快至少3倍。因此在Java上若要使用Base64,这个Java 8底下的java .util套件所提供的Base64类别绝对是首选!

 

转自:(8条消息) Java如何进行Base64的编码(Encode)与解码(Decode)?(*)_Firm陈的博客-CSDN博客_java decode解码

posted @   信铁寒胜  阅读(853)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示