懒人菜鸟入门Java系列-习惯性封装常用方法,方便开发过程中调用
注释: Java版本-1.8
* @Author wuwenchao
* @Version 1.0.0
* @Date 2022/4/29 10:07
*/
import java.io.UnsupportedEncodingException;
import java.util.Base64;
/**
* 封装Java Util包Base64方法
*
* @author wuwenchao
* @Date 2022-04-29 10:07
**/
public class JavaBase64Utils {
public static final String encodingUTF_8 = "UTF-8";
public static Base64.Encoder encoder;
public static Base64.Decoder decoder;
static {
decoder = Base64.getDecoder();
encoder = Base64.getEncoder();
}
/**
* byte[] Base64编码
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static byte[] encodeBase64(byte[] bytes) {
return encoder.encode(bytes);
}
/**
* 字符串 Base64编码
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static String encodeBase64(String source) {
byte[] bytes = encodeBase64(source.getBytes());
try {
return new String(bytes, encodingUTF_8);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return null;
}
/**
* byte[] Base64编码为 字符串
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static String encodeBase64String(byte[] bytes) {
return encoder.encodeToString(bytes);
}
/**
* 字符串 Base64编码为 byte[]
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static byte[] encodeBase64Byte(String source) {
byte[] bytes = encodeBase64(source.getBytes());
return bytes;
}
/**
* Base64Byte 解码
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static byte[] decodeBase64(byte[] bytes) {
return decoder.decode(bytes);
}
/**
* Base64字符串 解码为 byte[]
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static byte[] decodeBase64Byte(String string) {
return decoder.decode(string.getBytes());
}
/**
* Base64Byte 解码为字符串
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static String decodeBase64String(byte[] bytes) {
try {
return new String(decoder.decode(bytes),encodingUTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* Base64字符串 解码
*
* @Author wuwenchao
* @Date 2022/4/29 10:11
*/
public static String decodeBase64(String string) {
byte[] decode = decodeBase64(string.getBytes());
try {
return new String(decode, encodingUTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}