更改字符串格式


  1. import
    java.io.UnsupportedEncodingException;
  2. public class ChangeCharset {
    
  3. //7位ASCII字符,也叫做ISO646-US,Unicode字符集的基本拉丁快
  4. public static final String US_ASCII ="US-ASCII";
    
  5. //ISO拉丁字母表No.1,也叫做ISO-LATIN-1
  6. public static final String ISO_8859_1="ISO-8859-1";
    
  7. //8位UCS轉換格式
  8. public static final String UTF_8="UTF-8";
    
  9. //16位UCS轉換格式,Big Endian(最低地址存放高位字節)字節順序
  10. public static final String UTF_16BE="UTF-16BE";
    
  11. //16位UCS轉換格式,Litter Endian(最高地址存放低位字節)
  12. public static final String UTF_16LE ="UTF-16LE";
    
  13. //16位UCS轉換格式,字節順序由可選的字節順序標記來標識
  14. public static final String UTF_16 = "UTF-16";
  15. //中文超大字符集
  16. public static final String GBK = "GBK";
  17. //
  18. public static final String GB2312 ="GB2312";
  19. public String changeCharSet(String str,String newCharset) throws UnsupportedEncodingException{
  20. if(str!=null){
  21. //用默認字符編碼解碼字符串,與系統相關,中文Windows默認爲GB2312
  22. byte[] bs =str.getBytes();
  23. //用新的字符編碼生成字符串
  24. return new String(bs,newCharset);
  25.         }
  26. return null;
  27.     }
  28. public String changeCharset(String str,String oldCharset,String newCharset) throws UnsupportedEncodingException{
  29. if(str != null){
  30. //用源字符編碼解碼字符串
  31. byte[] bs = str.getBytes(oldCharset);
  32. return new String(bs,newCharset);
  33.         }
  34. return null;
  35.     }
  36. public String toASCII(String str) throws UnsupportedEncodingException{
  37. return this.changeCharSet(str, US_ASCII);
  38.     }
  39. public String toISO_8859_1(String str) throws UnsupportedEncodingException{
  40. return this.changeCharSet(str, ISO_8859_1);
  41.     }
  42. public String toUTF_8(String str) throws UnsupportedEncodingException{
  43. return this.changeCharSet(str, UTF_8);
  44.     }
  45. public String toUTF_16BE(String str) throws UnsupportedEncodingException{
  46. return this.changeCharSet(str, UTF_16BE);
  47.     }
  48. public String toUTF_16LE(String str) throws UnsupportedEncodingException{
  49. return this.changeCharSet(str, UTF_16LE);
  50.     }
  51. public String toUTF_16(String str) throws UnsupportedEncodingException{
  52. return this.changeCharSet(str, UTF_16);
  53.     }
  54. public String toGBK(String str) throws UnsupportedEncodingException{
  55. return this.changeCharSet(str, GBK);
  56.     }
  57. public String toGB2312(String str) throws UnsupportedEncodingException{
  58. return this.changeCharSet(str, GB2312);
  59.     }
  60. }

將字符串轉換其他格式的前提是將其轉換爲字節數組...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章