考虑以下操作顺序:
String pt = "abcd";
byte[] b64 = Base64.decodeBase64(pt.getBytes("UTF-8"));
ByteBuffer wrap = ByteBuffer.wrap(b64);
CharBuffer decode = StandardCharsets.UTF_8.decode(wrap);
ByteBuffer encode = StandardCharsets.UTF_8.encode(decode);
byte[] bytes = new byte[encode.remaining()];
encode.get(bytes);
String x = Base64.encodeBase64String(bytes); // "ae+/vR0="
为什么pt
和x
不相等?
我使用这些功能错了吗?发生了什么事?
答案 0 :(得分:0)
据我所知,您希望将某些字符串编码为base64格式并将其解码为相同的字符串。
<强>代码:强>
public static void main(String[] args) {
final String pt = "abcd";
final byte[] b64 = Base64.encodeBase64(pt.getBytes(StandardCharsets.UTF_8));
System.out.println(new String(b64, StandardCharsets.US_ASCII));
final String x = new String(Base64.decodeBase64(b64), StandardCharsets.UTF_8);
System.out.printf("pt: %s -- x: %s", pt, x);
}
或强>
public static void main(String[] args) {
final String pt = "abcd";
final ByteBuffer buffer = StandardCharsets.UTF_8.encode(pt);
final byte[] base64 = Base64.encodeBase64(buffer.array());
System.out.println(new String(base64));
final String x = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Base64.decodeBase64(base64))).toString();
System.out.printf("pt: %s -- x: %s", pt, x);
}
<强>结果:强>
YWJjZA==
pt: abcd -- x: abcd