2011-12-04 47 views
2

我有一個字符串cityName我解碼成字節如下:字符串轉換爲字節,並再次

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

...某處存儲字節。當我檢索這些字節時,我怎樣才能將它們解碼回字符串?

回答

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"); 
} 
+0

你不需要使用'Charset.forName( 「UTF-8」);'剛使用「UTF-8」正常工作。 – Jon

+0

他們都工作。 –

+1

只是說,使用普通的'字符串'看起來更好。但它取決於你。 – Jon

0

像這樣:

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

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