文章字数:341,阅读全文大约需要1分钟
java
程序中经常会有中文乱码的问题,通常都是字符编码的问题。这次系统性的了解一下这个问题
发生原因
字符编码的问题主要发生在编码和解码使用了不同的编码方式,体现在代码上就是
使用相同的字符编码解码和编码
1
2
3
4String test = new String("abc123阿布才");
byte[] testByte = test.getBytes(Charset.forName("utf-8"));
String testRes = new String(testByte, Charset.forName("utf-8"));
System.out.println("testRes = " + testRes);结果:
1
testRes = abc123阿布才
使用不同的字符编码解码和编码
1
2
3
4
5String test = new String("abc123阿布才");
// 这里变成了gbk编码
byte[] testByte = test.getBytes(Charset.forName("gbk"));
String testRes = new String(testByte, Charset.forName("utf-8"));
System.out.println("testRes = " + testRes);结果
1
testRes = abc123������
默认编码
程序内部交互一般不会出现字符编码的问题,因为编码和解码都会默认使用内部的默认编码。所以解析和编码是同一种编码类型。但是如果与其它程序交互,因为两个程序的默认编码不同则可能导致这种问题。
- 获取
jvm
当前默认字符编码1
System.out.println(System.getProperty(file.encoding));
无参的String.getBytes()
和new String(byte[])
使用的都是默认编码