IO_File_字符集_乱码[Java]

IO_File_字符集_乱码


**字符集 :**Java字符使用16位的双字节存储,但是在实际文件存储的数据有各种字符集,需要正确操作,否则就有乱码的发生。

字符集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package cn.io;

import java.io.UnsupportedEncodingException;

/**
* 编码:字符串-->字节
* @author HQF
*
*/
public class ContentEncode {

public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
String msg = "性命 生命 使命";
//编码:字节数组
byte[] datas = msg.getBytes();
System.out.println(datas.length);

//解码:字符串 String(byte[] bytes , int offset , int length , String charsetName)
msg = new String(datas , 0 , datas.length , "GBK");
System.out.println(msg);

//乱码:
//1. 字节数不够
msg = new String(datas , 0 , datas.length-1, "GBK");
System.out.println(msg);

//2. 字符集不统一
msg = new String(datas , 0 , datas.length-1, package cn.io;

import java.io.UnsupportedEncodingException;

/**
* 编码:字符串-->字节
* @author HQF
*
*/
public class ContentEncode {

public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
String msg = "性命 生命 使命";
//编码:字节数组
byte[] datas = msg.getBytes();
System.out.println(datas.length);

//解码:字符串 String(byte[] bytes , int offset , int length , String charsetName)
msg = new String(datas , 0 , datas.length , "GBK");
System.out.println(msg);

//乱码:
//1. 字节数不够
msg = new String(datas , 0 , datas.length-1, "GBK");
System.out.println(msg);

//2. 字符集不统一
msg = new String(datas , 0 , datas.length-1, "utf8");
System.out.println(msg);

}

}


1
2
3
4
5
14
性命 生命 使命
性命 生命 使? // 因为字节不够
???? ???? ?? 14
性命 生命 使命
性命 生命 使? // 因为字节不够
???? ???? ?? // 因为字符集不统一