2013-01-03 141 views
2

在一个PlayN项目,我有以下的Java代码字节缓冲区为字符串GWT

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(); 

能正常工作在Java中,但是当我尝试使用GWT编译它,我得到:

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

在GWT中,在ByteBuffer中获取一个String(用UTF-8编码)的正确方法是什么?

+1

'ByteBuffer' [不支持](https://developers.google.com/web-toolkit/doc/latest/RefJreEmulation)所以它怎么不会早点失效?你是否正在使用一些第三方库来仿效客户端的ByteBuffer? –

+0

哎呀,是的,我忘了提及:我使用模拟java.nio的PlayN(主要是Buffers),请参阅https://github.com/threerings/playn/tree/master/html/super/playn/super/java – AndresQ

回答

4

使用ByteBuffer#get(byte[])作为byte[]将字节从ByteBuffer中取出后,您应该能够使用new String(bytes, "UTF-8")
此构造函数String连同getBytes(String)以UTF-8和ISO-8859-1实现。

+0

我一直在寻找一个非常复杂的解决方案,实际上就是这么简单......谢谢! – AndresQ

+0

如果您查看gwt super-source,您会看到String默认为UTF-8;不过,如果这是共享代码,Thomas的答案就是跨平台的正确解决方案。 Nit:Gwt还支持使用“ISO-LATIN-1”的拉丁:) – Ajax