1: 编码表由来
计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。这就是编码表。
2:常见的字符集
ASCII:美国标准信息交换码。
用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表
用一个字节的8位表示。
GB2312:中国的中文编码表。最多两个字节编码所有字符
GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的
字符码。所有的文字都用两个字节来表示。
UTF-8:变长的编码方式,可用1-4个字节来表示一个字符
3: 转换流
转换流提供了在字节流和字符流之间的转换
java中提供两个转换流
InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
4: 代码
InputStreamReader使用
public static void main(String[] args) throws Exception {
//1: 创建流的对象,指明操作的文件
FileInputStream fis = new FileInputStream("a.txt");
//这种情况使用系统默认的字符集 (字节输入流转为字符输入流)
// InputStreamReader isr = new InputStreamReader(fis);
//2: 这种可以指明使用的字符集
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
//3: 读取数据
char[] cbuff = new char[1024];
int len;
while ((len = isr.read(cbuff)) != -1) {
//字节数组转为字符串
String str = new String(cbuff, 0, len);
System.out.println(str);
}
//4: 流的关闭
isr.close();
}
5: 转换流的使用
public static void main(String[] args) throws Exception {
//1.创建file的对象,指明操作的文件
File file1 = new File("a.txt");
File file2 = new File("C:\\Users\\root\\Desktop\\b.txt");
//2: 创建输入输出流的对象
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
//3: 使用转换流
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//2.读写过程
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
//3.关闭资源
isr.close();
osw.close();
}