字符输入流(Reader)和字符输出流(Writer)

字符输入流(Reader)

字符流和字节流差不多,只不过字符流是由字符组成。

//因为Reader是抽象类,所以使用时要引用子类的地址
Reader reader = new FileReader("F:\\aa\\test.txt");

案例

public class FileReaderDemo {
    public static void main(String[] args) {
        try {
            demo2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //一次读一个字符
    public static void demo1() throws IOException {
        Reader reader = new FileReader("F:\\aa\\test.txt");
        int date;
        while ((date = reader.read()) != -1) {
            System.out.print((char) date);
        }
    }

    //一次读多个字符
    public static void demo2() throws IOException {
        Reader reader = new FileReader("F:\\aa\\test.txt");
        char[] chars = new char[4];
        int date = reader.read(chars);
        System.out.println(date);
        System.out.println(new String(chars));
    }

    //循环读取,若是想要一次读完全部内容,可以把char[100]的值设置大一点,这样就不用循环读取
    public static void demo3() throws IOException {
        Reader reader = new FileReader("F:\\aa\\test1.txt");
        char[] chars = new char[100];
        int date;
        while ((date=reader.read(chars)) != -1){
            System.out.println(new String(chars));
            chars = new char[100];
            System.out.println(date);
        }
    }
}

字符输出流(Writer)

//true是追加,不会覆盖源文件
Writer writer = new FileWriter("F:\\aa\\test.txt",true);
public class FileWriteDemo {
    public static void main(String[] args) {
        try {
            demo();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void demo() throws IOException {
        Writer writer = new FileWriter("F:\\aa\\test.txt",true);//true是追加,不会覆盖源文件
        writer.write("这是个神马玩意");
        writer.write("今天要去干嘛");
        writer.flush();//刷新缓冲区
    }
}

字符流和字节流差不多,只不过一个是以字符为单位,一个是以字节为单位。要是不懂的可以看看博主上一篇字节流的文章。
字节流链接.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值