字符流介绍

Reader:字符输入流

Reader是IO库提供到的一个输入流基类

和InputStream的区别是:InputStream是一个字节流,操作的是以byte为单位读取

Reader是一个字符流,操作的是以char为单位读取

Reader的声明方式:

public abstract class Reader implements Readable, Closeable

读取方法:

public int read() throws IOException
public int read(char cbuf[]) throws IOException
public int read(char cbuf[], int off, int len) throws IOException
public int read(java.nio.CharBuffer target) throws IOException

Write:字符输出流

字符输出流

Writer操作的是字符,以char为单位进行操作

OutputStream操作的是字节,以byte为单位操作

Writer操作带有编码装换器的OutputStream

Reader操作带有编码转换器的InputStream

Writer的声明形式:

public abstract class Writer implements Appendable, Closeable, Flushable {

提供的方法:

image.png

 

FileReader:从磁盘中读取数据

关于构造函数:当路径不存在时,会抛出FileNotFoundExeption异常

读取操作:

            //读取数据
            int read = fd.read();
            System.out.println((char) read);

            /**
             * int read(char cbuf[]) throws IOException
             * 批量读取操作
             * 读取的数据放入char数组中
             * 返回结果表示读取数据的有效个数
             */
            char[] chars = new char[12];
            int read1 = fd.read(chars);
            System.out.println(new String(chars,0,read1));

            /**
             * int read(char cbuf[], int offset, int length)
             * 批量读取
             */
            fd.read();

FileWriter操作:向磁盘文件中写入数据

image.png

 

构造函数注意:
1、如果文件不存在可以自动创建,如果目录不存在,则抛出异常

2、如果需要将写入的数据以追加的形式存储,需要传递append参数为true

方法介绍:

        FileWriter fw = null;
        try {
            fw = new FileWriter(path,true);
            /**
             * void write(int c)
             * 每次写入一个字符的ASCII码
             */
//            fw.write('a');

            /**
             * void write(char cbuf[])
             * 批量写入
             * 将char数组内容写入
             */
            char[] chars = {'a', 'b', 'c'};
//            fw.write(chars);

            /**
             * void write(char cbuf[], int off, int len)
             * 批量写入char数组
             */
//            fw.write(chars,0,3);

            /**
             * void write(String str)
             * 写入字符串
             */
//            fw.write("hello");

            /**
             * void write(String str, int off, int len)
             * 写入部分字符串
             * off指定字符串的偏移量 len表示写入的长度
             */
//            fw.write("hello",0,5);

            fw.append(" tulun");

            fw.flush();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值