• java 的三种 Base64


    定义: 二进制文件可视化

    Base64 是一种能将任意二进制文件用 64 种字元组合成字串的方法, 彼此之间是可以互相转换的. 也常用来表示字串加密后的内容, 例如电子邮件 (很多文本混杂大量 加号、/、大小写字母、数字和等号,一看就知道是 Base64)

    Base64 编码步骤:

    第一步,将每三个字节作为一组,一共是24个二进制位

    第二步,将这24个二进制位分为四组,每个组有6个二进制位 (因为 6 位 2 进制最大数为 63)

    第三步,在每组前面加两个00,扩展成32个二进制位,即四个字节

    第四步,根据序号表(0-63),得到扩展后的每个字节的对应符号就是Base64的编码值

    sun 包下的 BASE64Encoder

    早期在 Java 上做 Base64 的编码与解码, 会使用到 JDK 里的 sun.misc 套件下的 BASE64Encoder 和 BASE64Decoder 这两个类, 缺点是编码和解码的效率不高

    final BASE64Encoder encoder = new BASE64Encoder();
    final BASE64Decoder decoder = new BASE64Decoder();
    final String text = "字串文字";
    final byte[] textByte = text.getBytes("UTF-8");
    //编码
    final String encodedText = encoder.encode(textByte);
    System.out.println(encodedText);
    //解码
    System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    apache 包下的 Base64

    比 sun 包更精简,实际执行效率高不少, 缺点是需要引用 Apache Commons Codec, 但 tomcat 容器下开发, 一般都自动引入可直接使用.

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

    util 包下的 Base64 (jdk8)

    java 8 的 java.util 包下 Base64 类, 可用来处理 Base64 的编码与解码

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

    Java 8 提供的 Base64 效率最高. 实际测试编码与解码速度, Java 8 的 Base64 要比 sun包下的要快大约 11 倍,比 Apache 的快大约 3 倍.

  • 相关阅读:
    python环境搭建
    还在肉眼找bug??赶紧进来!!!程序员一定要学的调试技巧.
    C++基础知识
    Azkaban集群模式部署
    PyTorch-线性回归
    C#在并发编程使用Frozen来确保线程安全性
    B. Jellyfish and Game-Codeforces Round 902 (Div. 2)
    go切片和指针切片
    路由器配置DMZ主机映射
    常用工具类----HttpClient
  • 原文地址:https://blog.csdn.net/howeres/article/details/125478101