一、前言
继上一篇写完字节编码内容后,现在分析在Java中各字符编码的问题,并且由这个问题,也引出了一个更有意思的问题,笔者也还没有找到这个问题的答案。也希望各位园友指点指点。
二、Java字符编码
直接上代码进行分析似乎更有感觉。
public class Test { public static String stringInfo(String str, String code) throws Exception { byte[] bytes = null; if (code.equals("")) // 使用缺省编码格式 bytes = str.getBytes(); else // 使用指定编码格式 bytes = str.getBytes(code); StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { // 转化为十六进制 sb.append(Integer.toHexString(bytes[i] & 0xff).toUpperCase() + " "); } // 对最后一个空格做处理(为了显示美观) String info = sb.toString().substring(0, sb.toString().length() - 1); // 组合返回 StringBuffer result = new StringBuffer(); result.append(bytes.length); result.append("["); result.append(info); result.append("]"); return result.toString(); } public static void main(String[] args) throws Exception { String left = "("; String right = ") : "; String[] strs = {"L", "LD", "李", "李邓"}; String[] codes = {"ASCII", "ISO-8859-1", "GB2312", "GBK", "Unicode", "UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE", ""}; for (String code : codes) { for (String str : strs) { System.out.println(str + left + (!code.equals("") ? code : "default") + right + stringInfo(str, code)); } System.out.println("---------------------------------------"); } } }