s-day10-转换流_指定编码读取(InputStreamReader)
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package com.inmind.transfer_stream02;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/*
|
||||
9.编码表的介绍
|
||||
编码:将字符转换成字节(类似加密)
|
||||
解码:将字节转换成字符(类似解密)
|
||||
|
||||
编码表:将每个国家的文字和二进制对应起来
|
||||
|
||||
ASCII 使用1个字节表示字符(第一位一定是0表示正数),0~127
|
||||
ISO-8859-1 使用1个字节表示字符,包扩了ASCII的,表示拉丁,欧洲的语言,不包含中文
|
||||
|
||||
gb2312: 使用2个字节表示1个字符,7000个简体中文和符号
|
||||
big5: 使用2个字节表示繁体字,片假名
|
||||
|
||||
GBK(国标码),使用2个字节表示1个字符,涵盖2万多个中文,繁体字完全兼容ASCII
|
||||
|
||||
unicode(万国码) u+0000到U+10FFFF的字符,包含110万字符,包含所有国家的文字
|
||||
|
||||
utf-8 :使用1,2,3,4个字节表示字符(3个字节表示1个中文)
|
||||
|
||||
utf-16 :使用2 ,4个字节表示字符
|
||||
|
||||
utf-32 :使用4个字节表示字符,比较占用内存
|
||||
|
||||
注意:
|
||||
1.GBK针对国内的字符进行编解码操作,它前128个字符完全兼容ascii,一个中文占2个字节
|
||||
2.utf-8针对国际的字符进行编解码操作,它前128个字符完全兼容ascii,一个中文占3个字节
|
||||
-------------------------------------------------------------------------------
|
||||
转换流_指定编码读取(InputStreamReader)
|
||||
|
||||
InputStreamReader是从字节流到字符流的桥梁:解码
|
||||
|
||||
构造方法:
|
||||
InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader。
|
||||
InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。
|
||||
|
||||
常用方法:
|
||||
close()
|
||||
int read();
|
||||
int read(char[] chars)
|
||||
|
||||
注意:转换流的作用是指定编码方式去读写文件
|
||||
|
||||
|
||||
*/
|
||||
public class Demo07 {
|
||||
//指定GBK编码方式去读取指定文件
|
||||
public static void main(String[] args) throws Exception {
|
||||
//创建转换输入流,并指定gbk编码
|
||||
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_gbk.txt"),"GBK");
|
||||
char[] chars = new char[1024];
|
||||
int len;
|
||||
while ((len = isr.read(chars)) != -1) {
|
||||
System.out.println(new String(chars,0,len));
|
||||
}
|
||||
|
||||
isr.close();
|
||||
}
|
||||
|
||||
|
||||
//指定utf-8编码方式去读取指定文件
|
||||
public static void method() throws Exception {
|
||||
/*
|
||||
创建转换输入流
|
||||
InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader。
|
||||
*/
|
||||
// InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_utf8.txt"));
|
||||
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_utf8.txt"),"utf-8");
|
||||
//一次读一个字符或者字符数组
|
||||
int ch ;
|
||||
while ((ch = isr.read())!=-1){
|
||||
System.out.print((char) ch);
|
||||
}
|
||||
|
||||
isr.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user