IO流-转换流
转换流是字符流和字节流之间的桥梁
1.可以根据字符集一次读取多个字节
2.读取数据不会乱码
代码练习:
1.利用转换流按照指定字符编码读取
public class ConvertStreamDemo01 {public static void main(String[] args) throws IOException {/*利用转换流按照指定字符编码读取(了解)"D:\aaa\ex\gbkfile.txt"JDK11:淘汰了这种,有替代方案*//* InputStreamReader isr = new InputStreamReader(new FileInputStream("gbkfile.txt"),"GBK");int ch;while ((ch = isr.read()) != -1) {System.out.print((char) ch);}isr.close();*///替代方案FileReader fr = new FileReader("gbkfile.txt", Charset.forName("GBK"));int ch;while ((ch = fr.read()) != -1) {System.out.print((char) ch);}fr.close();} }
2.利用转换流按照指定字符编码写出
public class ConvertStreamDemo02 {public static void main(String[] args) throws IOException {/*利用转换流按照指定字符编码写出*//*OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"),"GBK");osw.write("你好你好");osw.close();*///替代FileWriter fw = new FileWriter("c.txt", Charset.forName("GBK"));fw.write("好了好了");fw.close();}}
3.将本地文件中的GBK文件,转换为UTF-8
public class ConvertStreamDemo03 {public static void main(String[] args) throws IOException {//1.JDK11以前的方案/* InputStreamReader isr = new InputStreamReader(new FileInputStream("b.txt"),"GBK");OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d.txt"),"UTF-8");int b;while ((b = isr.read()) != -1){osw.write(b);}osw.close();isr.close();*///2.替代方案FileReader fr = new FileReader("b.txt", Charset.forName("GBK"));FileWriter fw = new FileWriter("e.txt",Charset.forName("UTF-8"));int b;while ((b = fr.read()) != -1){fw.write(b);}fw.close();fr.close();} }
4.利用字节流读取文件中的数据,每次读一整行,并且不能出现乱码
public class ConvertStreamDemo04 {/*利用字节流读取文件中的数据,每次读一整行,并且不能出现乱码*/public static void main(String[] args) throws IOException {//1.字节流在 读取中文时,会出现乱码,但是字符流不会//2.字节流是没有一次读取一整行的,但是字符缓冲流可以/*FileInputStream fis = new FileInputStream("a.txt");InputStreamReader isr = new InputStreamReader(fis);BufferedReader br = new BufferedReader(isr);String str = br.readLine();System.out.println(str);br.close();*/BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt")));String line;while ((line =br.readLine()) != null){System.out.println(line);}br.close();}}