转换流

也叫桥转换流 InputStreamReader / OutputStreamWriter

可将字节流转换为字符流

可设置字符的编码方式

InputStreamReader 

小案例:

package com.iopractise;

import java.io.*;

/**
 *InputStreamReader的使用
 */
public class Demo17 {
    public static void main(String[] args) throws IOException {
        // 1 创建InputStreamReader对象
        FileInputStream fis = new FileInputStream("d:\\ccc.txt");
        InputStreamReader isr = new InputStreamReader(fis, "utf-8");//如果文件的编码格式不是utf-8的话,是会出现乱码的。
        // 2 读取文件
        int data = 0;
        while((data = isr.read()) != -1){
            System.out.print((char)data);
        }
        // 3 关闭
        isr.close();//注意:关闭isr的时候,也就相当于将fis进行了关闭。
    }
}

  

运行结果:

中国加油!中国加油!中国加油!中国加油!中国加油!

中国加油!中国加油!中国加油!中国加油!中国加油!

OutputStreamWriter

package com.iopractise;

import java.io.*;
import java.security.acl.Owner;

/**
 *OutputStreamWriter
 */
public class Demo18 {
    public static void main(String[] args) throws IOException {
        //1.创建
        FileOutputStream fos = new FileOutputStream("d:\\info.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
        //2.写入
        for(int i=0;i<10;i++){
            osw.write("我爱北京,也爱我的家乡\r\n");
            osw.flush();
        }
        //3.关闭
        osw.close();
        System.out.println("执行完毕");


    }
}

  

运行结果:打开文件进行查看
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡
我爱北京,也爱我的家乡

  

posted @ 2021-02-07 22:36  ~码铃薯~  阅读(74)  评论(0编辑  收藏  举报