将字符串转换为字节,然后再转换回来

发布于 2024-12-19 14:46:40 字数 162 浏览 0 评论 0原文

我有一个字符串 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

青丝拂面 2024-12-26 14:46:40

使用 字符串(字节[],字符集)String(byte[], String) 构造函数。

byte[] rawBytes = /* whatevs */

try
{
    String decoded = new String(rawBytes, Charset.forName("UTF-8"));
    // or
    String decoded = new String(rawBytes, "UTF-8");
    // best, if you're using Java 7 (thanks to @ColinD):
    String decoded = new String(rawBytes, StandardCharsets.UTF_8);
}
catch (UnsupportedEncodingException e)
{
    // see http://stackoverflow.com/a/6030187/139010
    throw new AssertionError("UTF-8 not supported");
}

Use the String(byte[], Charset) or String(byte[], String) constructor.

byte[] rawBytes = /* whatevs */

try
{
    String decoded = new String(rawBytes, Charset.forName("UTF-8"));
    // or
    String decoded = new String(rawBytes, "UTF-8");
    // best, if you're using Java 7 (thanks to @ColinD):
    String decoded = new String(rawBytes, StandardCharsets.UTF_8);
}
catch (UnsupportedEncodingException e)
{
    // see http://stackoverflow.com/a/6030187/139010
    throw new AssertionError("UTF-8 not supported");
}
腹黑女流氓 2024-12-26 14:46:40

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.

无边思念无边月 2024-12-26 14:46:40

像这样:

String cityName = new String(cityByte,"UTF-8");

Like this:

String cityName = new String(cityByte,"UTF-8");
萌能量女王 2024-12-26 14:46:40

String s = new String(cityByte, "UTF-8");

String s = new String(cityByte, "UTF-8");

输什么也不输骨气 2024-12-26 14:46:40

试试这个: http://docs.oracle.com/ javase/6/docs/api/java/lang/String.html

String(byte[] bytes, String charsetName) 

Try this: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

String(byte[] bytes, String charsetName) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文