缓冲字符流、文件字符流

BufferedInputStream

字节缓冲输入流:

1.是一个高级流,内部维护一个缓冲区,默认8KB

2.读取文件数据时一次性尽可能读取到缓冲区大小的字节

3.read方法从缓冲区获取数据:当缓冲区全部读完,会再次从磁盘上读取数据存储到缓冲区

4.常用构造器  BufferedInputStream(InputStream is)  BufferedInputStream(InputStream is,int size)

public class BufferedInputStreamDemo01 {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        try{
            bis = new BufferedInputStream(
                new FileInputStream("D:/file1.txt"),10);

            int ch = bis.read();
            System.out.println((char)ch);
            //一次性读取多点字节   
            byte[] byte = new byte[10];
            int length = -1;
            for((length = bis.read(byte)) != -1){
                String str =new String(byte,0,length);
                 System.out.println(str);
            }    

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferOutputStream

字节缓冲输出:

1. 内部维护了一个字节数组作为缓冲区(缓存)  : 默认值是8KB
2. 当我们写数据时,是先写到缓存中的, 并不是直接写到磁盘上。当缓存满的情况下,再一次性将数据写到磁盘,从而减少了与磁盘的交互次数,提高了写出效率。
3.最后一次写入到缓存后,有可能没有装满,可以调用flush方法,将其强制写到磁盘上
4.构造器:BuffertOutputStream(OutputSream os)   BuffertOutputStream(OutputSream os,int size)size用于自定义缓冲区的大小
public class BufferedOutputStreamDemo01 {
    public static void main(String[] args) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("D:/file2.txt",true);
           bos new BufferOutStream(fos);

            bos.write('A');
            byte[] bytes = "hello word".getBytes("UTF-8");
            bos.write(bytes,0,bytes.length);
            bos.flush();
           
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                /*
                 * 多个流的关闭顺序: 应该先关闭高级流,然后再关低级流
                 * 不过,可以直接关闭高级流。
                 */
//                bos.close();
                fos.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值