Java: 转换流

转换流

1.定义

是字符流和字节流之间的桥梁。
分为:

  • 字符转换输入流(InputStreamReader
  • 字符转换输出流(OutputStreamWrite

2.作用

1.作用1:指定字符集读写

在jdk11时,这种方式被淘汰了。
案例1:利用转换流按照指定字符编码读取

 //创建对象并指定字符编码
        InputStreamReader isr = new InputStreamReader(new FileInputStream("G:\\JavaReview\\day33\\gbktxt.txt"), "GBK");

        //读取数据
        int ch;
        while ((ch = isr.read()) != -1) {
            System.out.print((char) ch);
        }
        //释放资源
        isr.close();

JDK11以后的代替方案为:

        FileReader fr = new FileReader("G:\\\\JavaReview\\\\day33\\\\gbktxt.txt", Charset.forName("GBK"));

        //读取数据
        int ch;
        while ((ch = fr.read()) != -1) {
            System.out.print((char) ch);
        }
        //释放资源
        fr.close();

案例3:使用转换流写出不同编码的文件

        //创建转换流对象
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("G:\\JavaReview\\day33\\gbktxt.txt"),"GBK");

        FileWriter fw = new FileWriter("G:\\JavaReview\\day33\\a.txt", Charset.forName("GBK"));
        //写入数据
        fw.write("你好");

        fw.close();

案例4:将本地文件中的GBK文件,转换成UTF-8
JDK11以前:

        //JDK11以前
        InputStreamReader isr = new InputStreamReader(new FileInputStream("G:\\JavaReview\\day33\\a.txt"),"GBK");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("G:\\JavaReview\\day33\\b.txt"),"UTF-8");

        int ch;
        while ((ch = isr.read()) != -1){
            osw.write(ch);
        }

        osw.close();
        isr.close();

JDK11以后:

        FileReader fr = new FileReader("G:\\JavaReview\\day33\\a.txt", Charset.forName("GBK"));
        FileWriter fw = new FileWriter("G:\\JavaReview\\day33\\c.txt");

        int b;
        while ((b = fr.read()) != -1){
            fw.write(b);
        }
        fw.close();
        fr.close();

2.作用2:字节流想要使用字符流中的方法

案例1:读取文件中的每一行,打印在控制台

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("G:\\JavaReview\\day33\\c.txt")));
        String line;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();

你可能感兴趣的:(Java,SE,java,开发语言)