How to convert ByteBuffer value into String
JAVA-ByteBuffer
Collapse
X
-
-
It depends what you have stored in the ByteBuffer (ints, doubles, chars, etc). You get() the data and print print it appropriatly.Originally posted by sweety mehraHow to convert ByteBuffer value into String
e.g. the following puts a string a ByteBuffer then gets part of it back
when run givesCode:// demo of byteBuffer import java.nio.*; class DemoByteBuffer{ public static void main(String[] args){ String s="hello sam"; System.out.println("s is " + s); // convert String s to Bytes and warp in ByteBuffer buf ByteBuffer buf = ByteBuffer.wrap(s.getBytes()); // convert another String to Bytes byte[] byte2 = (new String("hello tom").getBytes()); System.out.println("byte2 is " + new String(byte2)); // copy 3 bytes from buf position 6 to byte array position 6 buf.position(6); buf.get(byte2, 6, 3); System.out.println("byte2 is " + new String(byte2)); } }
s is hello sam
byte2 is hello tom
byte2 is hello sam
A good discussion is at
http://www.developer.c om/java/article.php/1449271Comment
Comment