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

时间:2011-12-04 20:50:04

标签: java string byte

我有一个字符串cityName,我将其解码为字节,如下所示:

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

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

5 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:0)

String class有一些构造函数接受一个字节数组,包括one that takes an array of bytes and a String representation of a charsetanother that takes a Charset object。如果String只是字节数组的一小部分,那么还有构造函数将String的偏移量和长度作为参数。

答案 2 :(得分:0)

像这样:

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

String(byte[] bytes, String charsetName)