Base64编码解码已经加入Java 8 类库的标准。
使用文档:https://www.runoob.com/java/java8-base64.html
编码解码示例:
import java.util.Base64;
import java.util.Base64.Decoder;
public class Test {
public static void main(String[] args) throws Exception {
String str = "锄禾日当午,汗滴禾下土。\n谁知盘中餐,粒粒皆辛苦。";
String base64_1 = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
System.out.println(base64_1);
System.out.println("*******");
String base64_2 = Base64.getMimeEncoder().encodeToString(str.getBytes("utf-8"));
System.out.println(base64_2);
System.out.println("*******");
Decoder decoder = Base64.getMimeDecoder();
byte[] bs_1 = decoder.decode(base64_1);
System.out.println(new String(bs_1, "utf-8"));
System.out.println("*******");
byte[] bs_2 = decoder.decode(base64_2);
System.out.println(new String(bs_2, "utf-8"));
}
}
打印结果:
6ZSE56a+5pel5b2T5Y2I77yM5rGX5ru056a+5LiL5Zyf44CCCuiwgeefpeebmOS4remkkO+8jOeykueykueahui+m+iLpuOAgg==
*******
6ZSE56a+5pel5b2T5Y2I77yM5rGX5ru056a+5LiL5Zyf44CCCuiwgeefpeebmOS4remkkO+8jOey
kueykueahui+m+iLpuOAgg==
*******
锄禾日当午,汗滴禾下土。
谁知盘中餐,粒粒皆辛苦。
*******
锄禾日当午,汗滴禾下土。
谁知盘中餐,粒粒皆辛苦。