详解Java如何进⾏Base64的编码(Encode)与解码
(Decode)
关于base64编码Encode和Decode编码的⼏种⽅式
Base64是⼀种能将任意Binary资料⽤64种字元组合成字串的⽅法,⽽这个Binary资料和字串资料彼此之间是可以互相转换的,⼗分⽅便。在实际应⽤上,Base64除了能将Binary资料可视化之外,也常⽤来表⽰字串加密过后的内容。如果要使⽤Java 程式语⾔来实作Base64的编码与解码功能,可以参考本篇⽂章的作法。
早期作法
早期在Java上做Base64的编码与解码,会使⽤到JDK⾥sun.misc套件下的BASE64Encoder和BASE64Decoder这两个类别,⽤法如下:
final BASE64Encoder encoder = new BASE64Encoder();
final BASE64Decoder decoder = new BASE64Decoder();
final String text = "字串⽂字";
final byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = de(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));
final BASE64Encoder encoder = new BASE64Encoder();
final BASE64Decoder decoder = new BASE64Decoder();
final String text = "字串⽂字";
final byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = de(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));
从以上程式可以发现,在Java⽤Base64⼀点都不难,不⽤⼏⾏程式码就解决了!只是这个sun.mis c套件所提供的Base64功能,编码和解码的效率并不太好,⽽且在以后的Java版本可能就不被⽀援了,完全不建议使⽤。
Apache Commons Codec作法
Apache Commons Codec有提供Base64的编码与解码功能,会使⽤到dec.binary套件下的Base64类别,⽤法如下:
final Base64 base64 = new Base64();
final String text = "字串⽂字";
final byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = deToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(base64.decode(encodedText), "UTF-8"));
final Base64 base64 = new Base64();
final String text = "字串⽂字";
decoderfinal byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = deToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(base64.decode(encodedText), "UTF-8"));
以上的程式码看起来⼜⽐早期⽤sun.mis c套件还要更精简,效能实际执⾏起来也快了不少。缺点是需要引⽤Apache Commons Codec,很⿇烦。
Java 8之后的作法
Java 8的java.util套件中,新增了Base64的类别,可以⽤来处理Base64的编码与解码,⽤法如下:
final Base64.Decoder decoder = Decoder();
final Base64.Encoder encoder = Encoder();
final String text = "字串⽂字";
final byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = deToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
final Base64.Decoder decoder = Decoder();
final Base64.Encoder encoder = Encoder();
final String text = "字串⽂字";
final byte[] textByte = Bytes("UTF-8");
//编码
final String encodedText = deToString(textByte);
System.out.println(encodedText);
/
/解码
System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
与sun.mis c套件和Apache Commons Codec所提供的Base64编解码器来⽐较的话,Java 8提供的Base64拥有更好的效能。实际测试编码与解码速度的话,Java 8提供的Base64,要⽐sun.mis c套件提供的还要快⾄少11倍,⽐Apache Commons Codec提供的还要快⾄少3倍。因此在Java上若要使⽤Base64,这个Java 8底下的java .util套件所提供的Base64类别绝对是⾸选!
到此这篇关于详解Java如何进⾏Base64的编码(Encode)与解码(Decode)的⽂章就介绍到这了,更多相关Java Base64编码与解码内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!