概述
- 转换流提供了在字节流和字符流之间的转换
- Java API提供了两个转换流:
InputStreamReader:将InputStream转换为Reader———>解码
OutputStreamWriter:将Writer转换为OutputStream———>编码
- 字节流中的数据都是字符时,转成字符流操作更高效。
- 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

InputStreamReader
实现将字节的输入流按指定字符集转换为字符的输入流。 需要和InputStream“套接”。
构造器
public InputStreamReader(InputStream in)public InputSreamReader(InputStream in,String charsetName)
如: Reader isr = new InputStreamReader(System.in,”gbk”); //“gbk”为编码集,使用该编码集解码
/*InputStreamReader的使用,实现字节的输入流到字符的输入流的转换*/public void test1() throws IOException {FileInputStream fis = new FileInputStream("dbcp.txt");// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集//参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用系统默认的字符集解码char[] cbuf = new char[20];int len;while((len = isr.read(cbuf)) != -1){String str = new String(cbuf,0,len);System.out.print(str);}isr.close();}
OutputStreamWriter
实现将字符的输出流按指定字符集转换为字节的输出流。 需要和OutputStream“套接”。
构造器
public OutputStreamWriter(OutputStream out)public OutputSreamWriter(OutputStream out,String charsetName)
public void test2() throws Exception {//1.造文件、造流File file1 = new File("dbcp.txt");File file2 = new File("dbcp_gbk.txt");FileInputStream fis = new FileInputStream(file1);FileOutputStream fos = new FileOutputStream(file2);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){//将文件isr通过utf-8读到char数组osw.write(cbuf,0,len);//将char数组通过gbk编码集写入到osw文件中}//3.关闭资源isr.close();osw.close();}
