文件编码

gbk

gbk 编码中文占用2个字节,英文占用1个字节

1
2
3
4
5
6
7
8
9
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "风间ABC";
byte[] bytes3 = s.getBytes("gbk");
// gbk 编码中文占用2个字节,英文占用1个字节
for (byte b : bytes3) {
// 把字节(转换成了int)以16进制的方式显示
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
}

提示:& 0xff 保留后8位置(一个字节8位,int占4个字节,展示时前面24位去掉)

utf-8

utf-8 编码中文占用3个字节,英文占用1个字节

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "风间ABC";
byte[] bytes1 = s.getBytes();// 转换成字节序列,用的是项目默认的编码 utf-8
for (byte b : bytes1) {
// 把字节(转换成了int)以16进制的方式显示
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
byte[] bytes2 = s.getBytes("utf-8");
// utf-8 编码中文占用3个字节,英文占用1个字节
for (byte b : bytes2) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
}

}

utf-16be

java 是双字节编码 utf-16be,java 中一个字符占两个字节
java 一个字符是否可以放一个汉字?可以,gbk编码的汉字

1
2
3
4
5
6
7
8
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "风间ABC";
byte[] bytes4 = s.getBytes("utf-16be");
// utf-16be 中文占两个字节,英文占两个字节
for (byte b : bytes4) {
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
}

字节序列转字符串

当你的字节序列是某种编码时,这个时候想把字节序列变成字符串,
也需要用这种编码方式,否则会出现乱码

1
2
3
4
5
6
7
8
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "风间ABC";
String str1 = new String(bytes4);// 用项目默认的编码
System.out.println(str1);

String str2 = new String(bytes4, "utf-16be");
System.out.println(str2);
}

项目间拷贝文件

文本文件就是字节序列,可以是任意编码格式
eclipse不同项目之间拷贝文件,编码不同会导致乱码,复制内容则会自动转换编码格式


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!