转换流是处理流的一种
种类: InputStreamReader和OutputStreamWriter
作用:提供字节流和字符流之间的转换
InputStreamReader:将字节的输入流转换为字符的输入流
OutputStreamWriter:将字符的输出流转化为字节的输出流
用后缀进行分析流的种类: 转换流的后缀为Reader和Writer,为字符流,读写的时候操作的是char型数组
解码: 字节,字节数组转化为字符串,字符数组。要用到InputSreamReader
编码: 字符串,字符数组转化为字节,字节数组。要用到OutputSreamWriter
字节字符之间的转化(比如字节的十进制为97转化为’a’)涉及到字符集的问题
处理文本文件时,输入层面的字节流用转换流(InputStreamReader)处理之后可以转化成以char为基本单位(字符流)进行输入
输出层面的字符流用转换流(OutputSreamWriter)处理之后可以转化成字节流写到文本文件中
字节流读入文本文件输出到控制台可能会乱码,但可以用转化流之后再输出到控制台
import java.io.*;
/**
* 用字节流读文本文件并用转换流处理后输出到控制台上,在write的时候换一种字符集(原文件是UTF-8),把字符按照gbk的方式转化成字节,目标文件就以gbk的方式存储
*/
public class Test {
public static void main(String[] args) {
InputStreamReader isr = null;
try {
FileInputStream fi=new FileInputStream("hello1.txt");
isr = new InputStreamReader(fi);//只传进去fi表示使用系统默认的字符集,IDEA中我们设置的是UTF-8;
//可以这么写:new InputStreamReader(fi,"UTF-8");参数2指明了字符集,""中也可以放别的字符集,指明了把字节转换成字符的方式
//指明什么字符集是根据文件保存的时候使用的字符集决定的(可以用notepad点击格式查看),现在要读也要用这种格式去读,如果用别的会发生乱码
char[] chars=new char[5];
int len;
while((len=isr.read(chars))!=-1){
String str=new String(chars,0,len);
System.out.print(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//还是只关闭最外层的流即可
try {
if(isr!=null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStreamReader isr1=null;//utf-8等同于UTF-8
OutputStreamWriter osw1=null;
try {
File file1=new File("hello1.txt");
File file2=new File("hello_gbk.txt");//没有会进行创建
FileInputStream fis1=new FileInputStream(file1);
FileOutputStream fos1=new FileOutputStream(file2);
isr1 = new InputStreamReader(fis1,"utf-8");
osw1 = new OutputStreamWriter(fos1,"gbk");
char[] chars1=new char[5];
int len1;
while((len1=isr1.read(chars1))!=-1){
osw1.write(chars1,0,len1);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(isr1!=null)
isr1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(osw1!=null)
osw1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果在IDEA中打开得到的文件,文件是乱码的,因为我们在IDEA中设置的是UTF-8,而得到的文件是gbk
但用Notepad++打开能进行正常的显示,因为可以自动识别文件的字符集