Encode String to UTF-8

Alex picture Alex · Apr 20, 2011 · Viewed 993.6k times · Source

I have a String with a "ñ" character and I have some problems with it. I need to encode this String to UTF-8 encoding. I have tried it by this way, but it doesn't work:

byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");

How do I encode that string to utf-8?

Answer

Amir Rachum picture Amir Rachum · Apr 20, 2011

How about using

ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)