1.编码和解码
编码: 把字符 --转成–> 对应的码值 比如: a —> 0110 0001
解码: 把码值 --解析–> 对应的字符 比如: 0110 0010 —> b
2.字符编码
什么是字符编码: 一套规则,字符和其码值之间对应的规则
比如: 字符a —> 97
字符A —> 65
字符0 —> 48
3.字符集
什么是字符集: 是指一个系统上支持的所有字符的集合,包括文字,文字、标点符号、图形符号、数字等
常见的字符集和常见的字符编码有哪些:
-
a.“ASCII字符集”: 包括英文字母,符号,阿拉伯数字等
其对应的字符编码,“ASCII编码”,在这个编码中所有的字符是占"一个字节" -
b.“GBxxxx"字符集
GB2312字符集: 包括常见简体汉字,大概7000多个
GBK字符集:包含常见的汉字(简体+繁体+日韩文字),大概20000多个
GBK18030字符集(最新字符集):包含各种汉字,少数民族的文字,大概70000多个
其对应的字符编码,“GBK编码”,在这个编码中一个中文占"两个字节” -
c.“Unicode"字符集(统一字符集)
其对应的字符编码,UTF-8,UTF-16,UTF-32,…
在"UTF-8"中一个中文占"三个字节” -
d.ISO-8859-1字符集(拉丁字符集,西欧国家的字符集)
我们以后的服务器Tomcat7以前默认使用的就是ISO-8859-1
4.编码引出的问题
idea工具默认使用的UTF-8编码,认为一个中文三个字节
这时候如果我们用idea读取一个GBK编码的文件,就会出现乱码!!
public class LuanMaDemo {
public static void main(String[] args) throws Exception {
//1.创建一个字符输入流
FileReader fr = new FileReader("3.txt"); //3.txt 使用GBK编码 你好 4个字节
//2.读取一个字符
int ch = fr.read();
System.out.println((char)ch);
//3.释放资源
fr.close();
}
}
由于编码不同(文件的编码和读取时的编码不同),引起了乱码问题
怎么解决这个问题呢???
a.文件也使用UTF-8编码
b.将idea的默认编码改成GBK
c.我们能否在读取文件时通过代码去指定使用何种编码呢?? 可以!!!(推荐的方式!!)
4.使用转换流InputStreamReader解决读取中文的问题
InputStreamReader 转换输入流
作用:可以在读取文件时,指定编码!
- 构造方法
public InputStreamReader(InputStream in,String charsetName);
//创建一个转换输入流,底层需要一个普通的字节流,charsetName表示指定的字符编码名字
public InputStreamReader(InputStream in);
//创建一个转换输入流,底层需要一个普通的字节流,默认使用idea的默认字符编码!
- 使用InputStreamReader读取不同编码的文件(代码演示)
public class InputStreamReaderDemo {
public static void main(String[] args) throws Exception {
//1.使用转换输入流读取文件
// InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");
InputStreamReader isr = new InputStreamReader(new FileInputStream("utf8.txt"),"UTF-8");
//2.读数据
int ch = isr.read();
System.out.println((char) ch);
ch = isr.read();
System.out.println((char) ch);
//3.释放资源
isr.close();
}
}
##### 5.使用转换流OutputStreamWriter写不同编码的中文
OutputStreamWriter 转换输出流
作用:可以在写文件,指定编码!!
- 构造方法
public OutputStreamWriter(OutputStream out,String charsetName);
//创建转换输出流,底层需要一个字节输出流,参数charsetName表示指定的编码名字
public OutputStreamWriter(OutputStream out);
//创建转换输出流,底层需要一个字节输出流,默认使用idea的默认字符编码!
- 输出指定编码的中文
public class OutputStreamWriterDemo {
public static void main(String[] args) throws Exception {
//1.创建一个OutputStreamWriter对象
// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("g.txt"),"GBK");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("u.txt"),"UTF-8");
osw.write("你好");
//3.释放资源
osw.close();
}
}
6.转换流的理解
7.练习:转换文件编码
转换文件编码
需求: 现有一个文件,编码为UTF-8,请编码将它转为GBK编码
分析:
a.使用UTF-8编码将文件读取出来
b.使用GBK编码写入到另外一个文件中
public class TestDemo {
public static void main(String[] args) throws Exception {
// 转换文件编码
// 需求: 现有一个文件,编码为UTF-8,请编码将它转为GBK编码
// 分析:
// a.使用UTF-8编码将文件读取出来
InputStreamReader isr = new InputStreamReader(new FileInputStream("11.txt"),"UTF-8");
// b.使用GBK编码写入到另外一个文件中
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("22.txt"),"GBK");
// c.复制文件
int ch = 0;
while ((ch = isr.read()) != -1) {
osw.write(ch);
}
// d.释放资源
osw.close();
isr.close();
}
}