What´s the difference between
"hello world".getBytes("UTF-8");
and
Charset.forName("UTF-8").encode("hello world").array();
? The second code produces a byte array with 0-bytes at the end in most cases.
What´s the difference between
"hello world".getBytes("UTF-8");
and
Charset.forName("UTF-8").encode("hello world").array();
? The second code produces a byte array with 0-bytes at the end in most cases.
Your second snippet uses
ByteBuffer.array()
, which just returns the array backing theByteBuffer
. That may well be longer than the content written to theByteBuffer
.Basically, I would use the first approach if you want a
byte[]
from aString
:) You could use other ways of dealing with theByteBuffer
to convert it to abyte[]
, but given thatString.getBytes(Charset)
is available and convenient, I'd just use that...Sample code to retrieve the bytes from a
ByteBuffer
: