可用的三种方式
1、
private final BASE64Encoder encoder = new BASE64Encoder();
private final BASE64Decoder decoder = new BASE64Decoder();
/**
* sun.misc base64使用
* @author zhangjianhui
* @date 2019/7/31.
*/
@Test
public void test() throws Exception{
String text = "壮丽的4界";
byte[] textByte = text.getBytes(DEFAULT_CHARSET);
// 编码
String encode2String = encoder.encode(textByte);
System.out.println("encode2String:" + encode2String);
// 解码
byte[] decode2Byte = decoder.decodeBuffer(encode2String);
// 源数据
System.out.println("text:" + new String(decode2Byte, DEFAULT_CHARSET));
}
2、
private final org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64();
/**
* apache base64使用
* @author zhangjianhui
* @date 2019/7/31.
*/
@Test
public void test2() throws Exception{
String text = "壮丽的4界";
byte[] textByte = text.getBytes(DEFAULT_CHARSET);
// 编码
String encode2String = base64.encodeToString(textByte);
System.out.println("encode2String:" + encode2String);
// 解码
byte[] decode2Byte = base64.decode(encode2String);
// 源数据
System.out.println("text:" + new String(decode2Byte, DEFAULT_CHARSET));
}
3、
private final Base64.Encoder encoder8 = Base64.getEncoder();
private final Base64.Decoder decoder8 = Base64.getDecoder();
/**
* java.util base64使用
* @author zhangjianhui
* @date 2019/7/31.
*/
@Test
public void test3() throws Exception{
String text = "壮丽的4界";
byte[] textByte = text.getBytes(DEFAULT_CHARSET);
// 编码
String encode2String = encoder8.encodeToString(textByte);
System.out.println("encode2String:" + encode2String);
// 解码
byte[] decode2Byte = decoder8.decode(encode2String);
// 源数据
System.out.println("text:" + new String(decode2Byte, DEFAULT_CHARSET));
}
测试编码与解码速度,Java 8提供的Base64,要比sun.mis c提供的快至少11倍,比Apache Commons Codec提供的快至少3倍。因此在Java上使用Base64,Java 8提供的Base64拥有更好的性能。
BASE64:
https://blog.youkuaiyun.com/kexuanxiu1163/article/details/97717969
JAVA NIO缓冲区:
https://blog.youkuaiyun.com/xialong_927/article/details/81044759