Java Io 之 编码

Java字符串编码一些知识总结:

package com.dcz.io;

import java.io.UnsupportedEncodingException;

public class EncodeDemo {

	public static void main(String[] args) throws UnsupportedEncodingException {

		String str = "中国ABC";
// 转换成字节数组是项目默认的编码GBK
byte[] byteArray = str.getBytes();
for(byte b : byteArray){
System.out.print(Integer.toHexString(b & 0xff) + " ");
} System.out.println(); // 显示转换为GBK编码
byte[] byteArray2 = str.getBytes("gbk");
for(byte b: byteArray2){
System.out.print(Integer.toHexString(b & 0xff) + " ");
} System.out.println(); // 显示转换为UTF-8编码(在UTF-8编码中,中文占用3个字节,英文占用一个字节)
byte[] byteArray3 = str.getBytes("utf-8");
for(byte b : byteArray3){
System.out.print(Integer.toHexString(b & 0xff) + " ");
} System.out.println(); // 显示转换为UTF-16be(在此编码上,中文和英文各站两个字节)
byte[] byteArray4 = str.getBytes("utf-16be");
for(byte b : byteArray4){
System.out.print(Integer.toHexString(b & 0xff) + " ");
} /**
* 当你的字节序列是某种编码时候,想把字节序列变成字符串也需要使用某种编码,否则乱码。
*/ System.out.println(); // 乱码原因是由于转换和反转编码不统一
String str1 = new String(byteArray3);
System.out.println(str1); // 不乱码原因是由于转换和反转使用了统一格式编码
String str2 = new String(byteArray3, "utf-8");
System.out.println(str2); } }

总结:从上面的测试代码中可以了解到字符乱码是和字符编码有直接关系。

上一篇:python egg文件解压


下一篇:The remote end hung up unexpectedly