import java.nio.charset.StandardCharsets; import java.util.Base64; public class Base64Example { public static void main(String[] args) { String originalString = "oa:123456"; // 使用Base64编码器 Base64.Encoder encoder = Base64.getEncoder(); // 将字符串转换为字节数组 byte[] encodedBytes = encoder.encode(originalString.getBytes(StandardCharsets.UTF_8)); // 将字节数组转换为字符串 String encodedString = new String(encodedBytes, StandardCharsets.UTF_8); System.out.println("原始字符串: " + originalString); System.out.println("Base64 编码后: " + encodedString); Base64.Decoder decoder = Base64.getDecoder(); byte[] decodedBytes = decoder.decode(encodedString); // 将解码后的字节数组转换为字符串 String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println("原始字符串: " + decodedString); } }
<dependencies> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.7</version> </dependency> </dependencies> import cn.hutool.core.codec.Base64; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; public class Base64Example2 { public static void main(String[] args) { String originalString = "oa:123456"; System.out.println(originalString); byte[] plain = StrUtil.bytes(originalString, CharsetUtil.CHARSET_UTF_8); String cipherText = Base64.encode(plain); System.out.println(cipherText); byte[] encData = Base64.decode(cipherText); String encStr = StrUtil.str(encData, CharsetUtil.CHARSET_UTF_8); System.out.println(encStr); } }
public static String getBase64Str(String originalString) { java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); byte[] encodedBytes = encoder.encode(originalString.getBytes(StandardCharsets.UTF_8)); return new String(encodedBytes); } public static String getOriginalStr(String base64Str) { java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); byte[] decodedBytes = decoder.decode(base64Str); return new String(decodedBytes, StandardCharsets.UTF_8); }
标签:originalString,Base64,UTF,String,base64,System,util From: https://www.cnblogs.com/tonggc1668/p/18422043