![](/img/trans.png)
[英]Fast alternative to java.nio.charset.Charset.decode(..)/encode(..)
[英]Java NIO Charset Encode Decode
请考虑以下操作顺序:
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
不相等?
我使用这些功能错了吗? 到底是怎么回事?
据我了解,您想将一些字符串编码为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.