当前位置:   article > 正文

Java之Base64_java base64工具类

java base64工具类

1.Base64概述:

      java.util.Base64 是JDK8提出的一个新特性,可以用来进行按照一定规则编码和解码

2.使用:

      编码:
          1.获取编码器
          2.对数据进行编码
      解码:
          1.获取解码器
          2.对数据进行解码


3.Base64工具类提供给了一套静态方法获取三种Base64编解码器


      基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/
      URL:输出被映射到一组字符A-Za-z0-9+_,输出是URL和文件
      MIME:输出映射到MIME友好格式,因为输出每行数据不超过76字符,并且使用【\r】跟随[\n]作为分隔

4,API:

      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 解码器

5.基本型

  1. public class Test1_基本型 {
  2. public static void main(String[] args) {
  3. // 使用基本型的编码器和解码器 对数据进行编码和解码
  4. //1.获取编码器
  5. Base64.Encoder encoder = Base64.getEncoder();
  6. //2.对字符串进行编码
  7. String str = "张三";
  8. String s = encoder.encodeToString(str.getBytes());
  9. //3.输出编码后的字符串
  10. System.out.println("编码后的字符串:"+s);
  11. //4.获取解码器
  12. Base64.Decoder decoder = Base64.getDecoder();
  13. //5.对编码后的字符串进行解码
  14. byte[] decode = decoder.decode(s);
  15. String s1 = new String(decode);
  16. //6.打印输出解码后的字符串
  17. System.out.println("解码后的字符串:"+s1);
  18. }
  19. }

6.URL型

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

7.MIME型

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/202964
推荐阅读
相关标签
  

闽ICP备14008679号