将String转换为字节,然后再返回

dar*_*sky 2 java string byte

我有一个字符串cityName,我解码成字节如下:

byte[] cityBytes = cityName.getBytes("UTF-8");

...并将字节存储在某处.当我检索这些字节时,如何将它们解码回字符串?

Mat*_*all 6

使用String(byte[], Charset)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");
}
Run Code Online (Sandbox Code Playgroud)

  • 在Java 7中,您也可以使用`StandardCharsets.UTF_8`. (3认同)