编码的验证gbk,utf...

来源:互联网 发布:西北师大知行学院贴吧 编辑:程序博客网 时间:2024/04/30 10:32

通过查找学习,了解有两种;

第一种:

使用Charset

String s="aa";

boolean flag=java.nio.charset.Charset.forName("GB2312").newEncoder().canEncode(s);


第二种:


  1. public static String getEncoding(String str) {      
  2.        String encode = "GB2312";      
  3.       try {      
  4.           if (str.equals(new String(str.getBytes(encode), encode))) {      
  5.                String s = encode;      
  6.               return s;      
  7.            }      
  8.        } catch (Exception exception) {      
  9.        }      
  10.        encode = "ISO-8859-1";      
  11.       try {      
  12.           if (str.equals(new String(str.getBytes(encode), encode))) {      
  13.                String s1 = encode;      
  14.               return s1;      
  15.            }      
  16.        } catch (Exception exception1) {      
  17.        }      
  18.        encode = "UTF-8";      
  19.       try {      
  20.           if (str.equals(new String(str.getBytes(encode), encode))) {      
  21.                String s2 = encode;      
  22.               return s2;      
  23.            }      
  24.        } catch (Exception exception2) {      
  25.        }      
  26.        encode = "GBK";      
  27.       try {      
  28.           if (str.equals(new String(str.getBytes(encode), encode))) {      
  29.                String s3 = encode;      
  30.               return s3;      
  31.            }      
  32.        } catch (Exception exception3) {      
  33.        }      
  34.       return "";      
  35.    }  
这个示例来自:http://blog.csdn.net/ge_zhiqiang/article/details/8211378

0 0
原创粉丝点击