java Base64编码解码工具类
package com.pro.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64Utils {
private static Logger logger = LoggerFactory.getLogger(Base64Utils.class);
public static String encode(String content) {
if (content == null) {
logger.warn(">>> Base64 编码内容为null!");
return null;
}
try {
return Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
logger.error("Base64 编码异常!", e);
}
return null;
}
public static String decode(String content) {
if (content == null) {
logger.warn(">>> Base64 解码内容为null!");
return null;
}
try {
byte[] decode = Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8));
return new String(decode, StandardCharsets.UTF_8);
} catch (Exception e) {
logger.error("Base64 编码异常!", e);
}
return null;
}
public static void main(String[] args) {
String txt = "{\"name\":\"S_GUID\",\"first_value\":\"5fb3a8e544be422\",\"value\":\"测试中文123test\"}";
String encode = encode(txt);
System.out.println("编码后的内容: " + encode);
String decode = decode(encode);
System.out.println("解码前的内容: " + txt);
System.out.println("解码后的内容: " + decode);
System.out.println("编码后是否相等: " + txt.equals(decode));
}
}