EDIT (2018): The edited sibling answer by @xinyongCheng is a simpler approach, and should be the accepted answer.
Your approach would be reasonable if you knew the bytes are in the platform's default charset. In your example, this is true because k.getBytes()
returns the bytes in the platform's default charset.
More frequently, you'll want to specify the encoding. However, there's a simpler way to do that than the question you linked. The String API provides methods that converts between a String and a byte[] array in a particular encoding. These methods suggest using CharsetEncoder/CharsetDecoder "when more control over the decoding [encoding] process is required."
To get the bytes from a String in a particular encoding, you can use a sibling getBytes() method:
byte[] bytes = k.getBytes( StandardCharsets.UTF_8 );
To put bytes with a particular encoding into a String, you can use a different String constructor:
String v = new String( bytes, StandardCharsets.UTF_8 );
Note that ByteBuffer.array()
is an optional operation. If you've constructed your ByteBuffer with an array, you can use that array directly. Otherwise, if you want to be safe, use ByteBuffer.get(byte[] dst, int offset, int length)
to get bytes from the buffer into a byte array.