在遇到中文汉字乱码的时候,我们经常需要确认当前汉字的编码以及需要转换成哪种编码,以下代码能很好的协助我们进行汉字的转码:
public static void printbytes(byte[] bytes){
int j = 0;
String s = "";
int len = bytes.length;
System.out.println("\n--------00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F--0123456789ABCDEF");
int i = 0;
for (i = 0; i < len; i++) {
if (i % 16 == 0) {
j++;
System.out.print(String.valueOf(String.valueOf((new StringBuffer("L ")).append(j)
.append(":\t"))));
s = " ";
}
if (bytes[i] >= 0x00 && bytes[i] < 0x10)
System.out.print("0");
System.out.print(Long.toString((long) bytes[i]& (long) 255, 16)+ " ");
char c = (char) bytes[i];
if (c > 0x20 && c < 0x80)
s += c;
else
s += "_";
if (i % 16 == 15)
System.out.println(s);
}
for (i %= 16; i < 16; i++)
System.out.print(" ");
if (!s.equals(""))
System.out.println(s);
System.out.println("--------00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F--0123456789ABCDEF");
}
public static void main(String arg[]){
String str="测试123";
try {
System.out.println(printbytes(str.getBytes("gbk")));
System.out.println(printbytes(str.getBytes("iso-8859-1")));
System.out.println(printbytes(str.getBytes("utf-8")));
} catch (Exception e) {
e.printStackTrace();
}
}
如果打印出来是(ASCII字符):B2 E2 CA D4 31 32 33 则当前的汉字("测试123")即为其编码。