将字符串转换为字节,然后再转换回来
我有一个字符串 cityName
,如下所示将其解码为字节:
byte[] cityBytes = cityName.getBytes("UTF-8");
...并存储字节某处。当我检索这些字节时,如何将它们解码回字符串?
I have a string cityName
which I decoded into bytes as follows:
byte[] cityBytes = cityName.getBytes("UTF-8");
...and stored the bytes somewhere. When I retrieve those bytes, how can I decode them back into a string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
字符串(字节[],字符集)
或String(byte[], String)
构造函数。Use the
String(byte[], Charset)
orString(byte[], String)
constructor.String 类 有一些接受字节数组,包括 采用字节数组和字符集的字符串表示形式 和 另一个采用 Charset 对象的。如果字符串只是字节数组的一小部分,还有一些构造函数将字符串的偏移量和长度作为参数。
The String class has a few constructors that accept an array of bytes, including one that takes an array of bytes and a String representation of a charset and another that takes a Charset object. There are also constructors that take the offset and length of the String as arguments, if the String is only a small section of the byte array.
像这样:
Like this:
String s = new String(cityByte, "UTF-8");
String s = new String(cityByte, "UTF-8");
试试这个: http://docs.oracle.com/ javase/6/docs/api/java/lang/String.html
Try this: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html