2017-04-11 8 views
0

は、次の一連の操作を考慮してください。のJava NIO文字セットエンコードデコード

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=" 

はなぜptx等しくありませんか?

私はこれらの関数を間違って使用していますか?何が起こっている?

答えて

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 
関連する問題