Java String.getBytes()詳解

基礎(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"));

參考文檔

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容