我有一个字符串cityName,我解码成字节如下:
byte[] cityBytes = cityName.getBytes("UTF-8");
...并将字节存储在某处.当我检索这些字节时,如何将它们解码回字符串?
使用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)