基礎(chǔ)概念
- Jvm 內(nèi)存中 String 的表示是采用 unicode 編碼
- UTF-8 是 Unicode 的實(shí)現(xiàn)方式之一
JDK
/**
* Encodes this {@code String} into a sequence of bytes using the named
* charset, storing the result into a new byte array.
*/
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException {
}
/**
* Constructs a new {@code String} by decoding the specified array of
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
* The length of the new {@code String} is a function of the charset, and
* hence may not be equal to the length of the byte array.
*/
public String(byte bytes[], Charset charset) {
}
getBytes(String charsetName)
對(duì)字符串按照 charsetName 進(jìn)行編碼(unicode→charsetName),返回編碼后的字節(jié)。
getBytes() 表示按照系統(tǒng)默認(rèn)編碼方式進(jìn)行。
String(byte bytes[], Charset charset)
對(duì)字節(jié)按照 charset 進(jìn)行解碼(charset→unicode),返回解碼后的字符串。
String(byte bytes[]) 表示按照系統(tǒng)默認(rèn)編碼方式進(jìn)行
示例
正確用法
String s = "浣犲ソ"; //這是"你好"的gbk編碼的字符串
String ss = new String(s.getBytes("GBK"), "UTF-8");
System.out.println(ss);
System.out.println( new String(str.getBytes("UTF-8"),"UTF-8"));
錯(cuò)誤用法
System.out.println( new String(str.getBytes("UTF-8"),"GBK"));