InputStreamReader、OutputStreamReader转换流的使用

InputStreamReader、OutputStreamReader转换流的使用

  1. 转换流:属于字符流
  • InputStreamReader :将一个字节的输入转化为字符的输入流
  • OutputStreamReader : 将一个字符的输入转化为字节的输入流
  1. 作用:提供字节流和字节流主之间的转换
  2. 编码:字节、字节数组转化为字符数组字符串
    解码:字符数组、字符串转化为字节、字节数组
public classInputStreamReaderTest{
    
    
	@Test
	public void test(){
    
    
		FileInputStream fis = new FileInputStream("hello.txt");
		//如果不指定自字符集使用默认的字符集
		//InputStreamReader isr = new InputStreamReader(fis);
		//具体使用哪个字符集,要看文件在保存的时候使用的是什么字符集
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		
		char[] buf = new char[20];
		int len;
		while((len = isr.read(buf)) != -1){
    
    
			String str = new String(buf,0,len);
			//输出到控制台,也可以输入到别的文件中
			System.out.println(str);
		}
		isr.close();
	}
}

在这里插入图片描述

转化文件的字符集

@Test 
public void test() throws IOException{
    
    
	File file1 = new File("hello1");
	File file2 = new File("hello1");
	
	FileInputStream fis = new FileInputStream(file1);
	FileOutputStream fos = new FileOutputStream(file2);
	
	InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
	OutPutStreamWriter osw = new OutPutStreamWriter(osw,"gbk");
    
    char[] cbuf = new char[20];
    int lenth= 0;
    //读写过程
    while((lenth = isr.read(buf)) != -1){
    
    
		osw.write(cbuf,0,len);
	}
	//关闭资源
	isr.close();
	osw.close();
}
  • 为了便于阅读将异常抛出,实际开发使用try catch finally 确保资源得到关闭。
  1. 字符集
  • ASCII:美国标准信息交换码,用一个字节的7位可以表示
  • ISO8859-1:拉丁码表,欧洲码表,用一个字节的8位表示
  • GB2313:中国的中文编码表,最多两个字节编码所有字符
  • GBK:中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码
  • Unicode:国际标准编码,融合了目前人类使用对的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节表示
  • UTF-8:变长的编码方式,可用1-4个字节来表示一个字符在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43941676/article/details/108412735