3

On a PlayN project I have the following Java code

import com.google.common.base.Charsets;
import java.nio.ByteBuffer;

ByteBuffer msg = ... // a ByteBuffer that contains a String
String s = Charsets.UTF_8.decode(msg).toString();

this works fine in Java, but when I try to compile it with GWT I get:

The method decode(ByteBuffer) is undefined for the type Charset

What's the proper way, in GWT, to obtain a String (encoded in UTF-8) that's inside a ByteBuffer?

AndresQ
  • 803
  • 5
  • 19
  • 1
    `ByteBuffer` [isn't supported](https://developers.google.com/web-toolkit/doc/latest/RefJreEmulation) so how come it doesn't fail earlier? Are you using some 3rd-party library that would emulate `ByteBuffer` on client-side? – Thomas Broyer Jan 03 '13 at 15:46
  • oops, yes, I forgot to mention: I'm using PlayN which emulates java.nio (mostly just Buffers), see https://github.com/threerings/playn/tree/master/html/super/playn/super/java – AndresQ Jan 03 '13 at 15:57

1 Answers1

5

You should be able to use new String(bytes, "UTF-8") after getting the bytes out of the ByteBuffer as a byte[] using ByteBuffer#get(byte[]).
This String constructor, along with getBytes(String), is implemented for UTF-8 and ISO-8859-1.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • I was looking for a very complex solution, and in fact it was that easy... thanks! – AndresQ Jan 03 '13 at 17:00
  • If you look in gwt super-source, you'll see that String defaults to UTF-8; though, if this is in shared code, Thomas' answer is the cross-platform correct solution. Nit: Gwt also supports latin using "ISO-LATIN-1" :) – Ajax Jan 04 '13 at 11:58