java中改变字符串编码
生活随笔
收集整理的這篇文章主要介紹了
java中改变字符串编码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
經(jīng)常因為字符編碼的問題而去網(wǎng)上搜一些改變字符編碼的東西,很麻煩,這次總結(jié)了一下比較全的改變字符編碼的方法以供參考。代碼如下:
代碼塊
import java.io.UnsupportedEncodingException;public class CharsetUtil {/** 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁塊 */public static final String US_ASCII = "US-ASCII";/** ISO 拉丁字母表 No.1,也叫作 ISO -LATIN -1 */public static final String ISO_8859_1 = "ISO-8859-1";/** 8 位 UCS 轉(zhuǎn)換格式 */public static final String UTF_8 = "UTF-8";/** 16 位 UCS 轉(zhuǎn)換格式,Big Endian(最低地址存放高位字節(jié))字節(jié)順序 */public static final String UTF_16BE = "UTF-16BE";/** 16 位 UCS 轉(zhuǎn)換格式,Little-endian (最高地址存放低位字節(jié))字節(jié)順序 */public static final String UTF_16LE = "UTF-16LE";/** 16 位 UCS 轉(zhuǎn)換格式,字節(jié)順序由可選的字節(jié)順序標(biāo)記來標(biāo)識 */public static final String UTF_16 = "UTF-16";/** 中文超大字符集 */public static final String GBK = "GBK";/*** 將字符編碼轉(zhuǎn)換成US -ASCII碼*/public String toASCII(String str) throws UnsupportedEncodingException{return this.changeCharset(str, US_ASCII);}/*** 將字符編碼轉(zhuǎn)換成ISO -8859 -1碼*/public String toISO_8859_1(String str) throws UnsupportedEncodingException{return this.changeCharset(str, ISO_8859_1);}/*** 將字符編碼轉(zhuǎn)換成UTF -8碼*/public String toUTF_8(String str) throws UnsupportedEncodingException{return this.changeCharset(str, UTF_8);}/*** 將字符編碼轉(zhuǎn)換成UTF -16BE碼*/public String toUTF_16BE(String str) throws UnsupportedEncodingException{return this.changeCharset(str, UTF_16BE);}/*** 將字符編碼轉(zhuǎn)換成UTF -16LE碼*/public String toUTF_16LE(String str) throws UnsupportedEncodingException{return this.changeCharset(str, UTF_16LE);}/*** 將字符編碼轉(zhuǎn)換成UTF -16碼*/public String toUTF_16(String str) throws UnsupportedEncodingException{return this.changeCharset(str, UTF_16);}/*** 將字符編碼轉(zhuǎn)換成GBK碼*/public String toGBK(String str) throws UnsupportedEncodingException{return this.changeCharset(str, GBK);}/*** 字符串編碼轉(zhuǎn)換的實現(xiàn)方法* @param str 待轉(zhuǎn)換編碼的字符串* @param newCharset 目標(biāo)編碼* @return* @throws UnsupportedEncodingException*/public String changeCharset(String str, String newCharset)throws UnsupportedEncodingException {if (str != null) {//用默認(rèn)字符編碼解碼字符串。byte[] bs = str.getBytes();//用新的字符編碼生成字符串return new String(bs, newCharset);}return null;}/*** 字符串編碼轉(zhuǎn)換的實現(xiàn)方法* @param str 待轉(zhuǎn)換編碼的字符串* @param oldCharset 原編碼* @param newCharset 目標(biāo)編碼* @return* @throws UnsupportedEncodingException*/public String changeCharset(String str, String oldCharset, String newCharset)throws UnsupportedEncodingException {if (str != null) {//用舊的字符編碼解碼字符串。解碼可能會出現(xiàn)異常。byte[] bs = str.getBytes(oldCharset);//用新的字符編碼生成字符串return new String(bs, newCharset);}return null;} }其中changeCharset 改變的是系統(tǒng)的默認(rèn)編碼,可用這種方法獲取從瀏覽器中g(shù)etPost獲取的數(shù)據(jù)
userid = charset.changeCharset(userid,"ISO-8859-1","UTF-8");總結(jié)
以上是生活随笔為你收集整理的java中改变字符串编码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java基础语法以及进制的转换
- 下一篇: html经典上中下三段的布局设计