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.基本型

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);
    }

}

6.URL型

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);
    }

}

7.MIME型

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);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值