2014-09-04 3 views

답변

4

두 번째 코드 단편은 ByteBuffer.array()을 사용하며 이는 ByteBuffer을 뒷받침하는 배열을 반환합니다. 콘텐츠가 보다에서 ByteBuffer으로 길어질 수 있습니다. 당신이 원하는 경우

는 기본적으로, 나는 첫 번째 방법을 사용하는 것 byte[]String A로부터 :) 당신 String.getBytes(Charset)이 가능하고 편리 주어진 사용하는 다른 byte[]로 변환하는 ByteBuffer 다루는 방법,하지만, 난 그냥 그것을 사용하는 거라고 ...

샘플 코드를 ByteBuffer에서 바이트를 검색 :

ByteBuffer buffer = Charset.forName("UTF-8").encode("hello world"); 
byte[] array = new byte[buffer.limit()]; 
buffer.get(array); 
System.out.println(array.length); // 11 
System.out.println(array[0]);  // 104 (encoded 'h') 
+0

그냥 "UTF-8"(즉'바이트 [] B1 = "안녕하세요!".getBytes을 관찰); 바이트 [] b2 = Charset.forName ("UTF-8"). encode ("hello world"). array();'. 'b1.length'는 11을 출력하고'b2.length'는 12를 출력합니다. –

+2

@Sandeep : 'ByteBuffer'는 아마도 12의 배킹 배열로 할당되었을 것입니다.'limit()'을 on 대신 ByteBuffer를 사용하면 11 바이트가됩니다. –