/**
* 测试某个字符串的编码,以解决乱码问题
* 切忌:一定先取得待测字符串的数组形式然后再测试,别转换为字符串!
* @param bt 要检测的字符的字节数组
* @param sample 是传入一些包含在待确定编码类型的字符串中的一段字符(需要在调用函数中人工输入!)
* 如果该参数为空字符串或null,则函数列出待确定编码类型字符串的字节数组的所有编码输出供选择
* 根据输出结果,就可以判断适合采用哪种编码形式
*/
public static void checkStringCharset(String sample, byte[] syd168) {
SortedMap<String, Charset> map = Charset.availableCharsets(); //创建哈希表
ArrayList<String> charSets = new ArrayList<String>(); //创建列表
//遍历哈希表元素
for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
Object key = it.next(); //获取编码名称
charSets.add(key.toString()); //添加到列表
}
//遍历列表元素
for (Object ob : charSets) {
//如果没输入样本数据,则逐个进行编码显示,以供人工判断编码类型
if (sample.equals("") || sample.equals(null)) {
try {
System.out.println("原字符串的[" + ob.toString() + "]编码输出为:" + new String(syd168, ob.toString()));
}
catch (IOException e1) {}
System.out.println("请根据输出结果,选择适合的编码方式进行处理");
System.out.println("可以用 new String(byte[],charset)可以解决乱码问题");
} else {//传入了样本数据
try {
String tmp = new String(syd168, ob.toString());//取得编码结果
if (tmp.indexOf(sample) >= 0) {//在编码字符串中找到了样本字符串,说明编码正确
System.out.println("待确定编码类型的字符串可能的编码为:" + ob.toString());
}
}
catch (UnsupportedEncodingException e) {}
}
}
}