Java 判别字符编码

Java 识别字符编码

 

public class EncodingUtils {

 

// 识别字符串编码

public static String getEncoding(String str) {

if (str == null || str.trim().length() < 1)

return "";

// 常用字符编码数组

String[] encodes = new String[] { "GBK", "ISO-8859-1", "GB2312",

"GB18030", "UTF-8" };

for (String encode : encodes) {

try {

// 匹配字符编码

if (str.equals(new String(str.getBytes(), encode))) {

// 返回编码名称

return encode;

} else {

continue;

}

} catch (Exception er) {

}

}

return "";

}

}