赞
踩
java.util.Base64 是JDK8提出的一个新特性,可以用来进行按照一定规则编码和解码
编码:
1.获取编码器
2.对数据进行编码
解码:
1.获取解码器
2.对数据进行解码
基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/
URL:输出被映射到一组字符A-Za-z0-9+_,输出是URL和文件
MIME:输出映射到MIME友好格式,因为输出每行数据不超过76字符,并且使用【\r】跟随[\n]作为分隔
public static Encoder getEncoder():基本型 base64 编码器
public static Decoder getDecoder():基本型 base64 解码器
public static Encoder getUrlEncoder():URL型 base64 编码器
public static Decoder getUrlDecoder():URL型 base64 解码器
public static Encoder getMimeEncoder():Mime型 base64 编码器
public static Decoder getMimeDecoder():Mime型 base64 解码器
- public class Test1_基本型 {
-
- public static void main(String[] args) {
- // 使用基本型的编码器和解码器 对数据进行编码和解码
- //1.获取编码器
- Base64.Encoder encoder = Base64.getEncoder();
- //2.对字符串进行编码
- String str = "张三";
- String s = encoder.encodeToString(str.getBytes());
- //3.输出编码后的字符串
- System.out.println("编码后的字符串:"+s);
-
- //4.获取解码器
- Base64.Decoder decoder = Base64.getDecoder();
- //5.对编码后的字符串进行解码
- byte[] decode = decoder.decode(s);
- String s1 = new String(decode);
- //6.打印输出解码后的字符串
- System.out.println("解码后的字符串:"+s1);
- }
-
- }

- public class Test2_URL型 {
-
- public static void main(String[] args) {
- // 使用URL型的编码器和解码器 对数据进行编码和解码
- // 1.获取编码器
- Base64.Encoder encoder = Base64.getUrlEncoder();
- // 2.对字符串进行编码
- String str = "name=zhangsan&password=123456";
- String s = encoder.encodeToString(str.getBytes());
- // 3.输出编码后的字符串
- System.out.println("编码后的字符串:"+s);
-
- // 4.获取解码器
- Base64.Decoder decoder = Base64.getUrlDecoder();
- // 5.对编码后的字符串进行解码
- byte[] decode = decoder.decode(s);
- String s1 = new String(decode);
- // 6.打印输出解码后的字符串
- System.out.println("解码后的字符串:"+s1);
- }
-
- }

- public class Test3_MIME型 {
-
- public static void main(String[] args) {
- // 使用URL型的编码器和解码器 对数据进行编码和解码
- // 1.获取编码器
- Base64.Encoder encoder = Base64.getMimeEncoder();
- // 2.对字符串进行编码
- String str = "name=zhangsan&password=123456name=zhangsan&password=123456";
- String s = encoder.encodeToString(str.getBytes());
- // 3.输出编码后的字符串
- System.out.println("编码后的字符串:"+s);
-
- // 4.获取解码器
- Base64.Decoder decoder = Base64.getMimeDecoder();
- // 5.对编码后的字符串进行解码
- byte[] decode = decoder.decode(s);
- String s1 = new String(decode);
- // 6.打印输出解码后的字符串
- System.out.println("解码后的字符串:"+s1);
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。