Java字符串编码和转换操作
簡(jiǎn)介: 在java程序的class里,字符串以u(píng)tf-8編碼保存。在程序處理中,需要進(jìn)行字符串編碼轉(zhuǎn)換時(shí),使用getByte指定編碼。
在java程序中,定義的字符串,在class文件中,字符串是以u(píng)tf-8進(jìn)行保存的。
public class Hello1 {public static void main(String [] args) {System.out.println("aaaa長(zhǎng)風(fēng)aaaa");} }編譯后,在class文件內(nèi),保存的字符串如下:
這里字符[長(zhǎng)]的utf8-的編碼:0xE995BF; [風(fēng)]的utf8-的編碼:0xE9A38E;
創(chuàng)建String時(shí)指定charset字符編碼
使用String(byte bytes[], String charsetName)構(gòu)造字符串。字節(jié)數(shù)組必須是charsetName指定的編碼。
String根據(jù)編碼要求進(jìn)行轉(zhuǎn)換
要進(jìn)行字符串編碼轉(zhuǎn)換,先使用String.getBytes(String charsetName) 獲取到指定編碼的字節(jié)數(shù)組,然后通過(guò)該數(shù)組在進(jìn)行處理。
說(shuō)明:
String.getBytes(String charsetName) throws UnsupportedEncodingExceptionEncodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.在java 1.7中,新加入了StandardCharsets類(lèi),專(zhuān)門(mén)用來(lái)標(biāo)示字符編碼
public final class StandardCharsets {public static final Charset US_ASCII = Charset.forName("US-ASCII");public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");public static final Charset UTF_8 = Charset.forName("UTF-8");public static final Charset UTF_16BE = Charset.forName("UTF-16BE");public static final Charset UTF_16LE = Charset.forName("UTF-16LE");public static final Charset UTF_16 = Charset.forName("UTF-16"); } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Java字符串编码和转换操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 火狐浏览器 Firefox 109.0.
- 下一篇: java美元兑换,(Java实现) 美元