,最近,我一直试图寻找一种判断Java程序中字符串编码格式的方法,同时,也查找了很多资料,设计了一个的程序,美中不足的是该方法对仅含有数字和英文字母的字符串无效。
原理:ASCII,GBK,UTF-8对数字和英文字母的编码相同,对其它字符编码不相同l,例如汉字等,UTF-16的编码跟前面三项都不同。
感兴趣的可以查看 Java中String字符串默认编码、Java几种常见的编码格式
源代码:
import java.nio.charset.Charset;
public class Encoding
{
public static String getEncoding(String str)
{
String encode;
encode = "UTF-16";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "ASCII";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return "字符串<< " + str + " >>中仅由数字和英文字母组成,无法识别其编码格式";
}
}
catch(Exception ex) {}
encode = "ISO-8859-1";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "GB2312";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "UTF-8";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
/*
*......待完善
*/
return "未识别编码格式";
}
public static void main(String[] args)
{
//获取系统默认编码
System.out.println("系统默认编码:" + System.getProperty("file.encoding")); //查询结果GBK
//系统默认字符编码
System.out.println("系统默认字符编码:" + Charset.defaultCharset()); //查询结果GBK
//操作系统用户使用的语言
System.out.println("系统默认语言:" + System.getProperty("user.language")); //查询结果zh
System.out.println();
String s1 = "hi, nice to meet you!";
String s2 = "hi, 我来了!";
System.out.println(getEncoding(s1));
System.out.println(getEncoding(s2));
}
}
测试结果,图1:
图1