缓冲字节流BufferedOutputStream、BufferedInputStream

详细介绍了Java IO中的缓冲字节流BufferedOutputStream、BufferedInputStream以及使用方式。

1 BufferedOutputStream缓冲区字节输出流

public class BufferedOutputStream
extends FilterOutputStream

特点:提供了缓冲区,缓冲区能够自动扩容,提高了写的效率。

1.1 构造器

public BufferedOutputStream(OutputStream out)

创建一个新的缓冲输出流,以将数据写入指定的底层输出流。out:底层输出流。

1.2 API方法

所有的方法都是继承和重写自父类FilterOutputStream的方法,没有提供新的方法。

void write(int b);
void write(byte[] b);
void write(byte[] b, int off, int len);
void flush();
void close();

2 BufferedInputStream缓冲区字节输入流

public class BufferedInputStream
extends FilterInputStream

特点:提供了缓冲区,缓冲区能够自动扩容,提高了读的效率。

2.1 构造器

public BufferedInputStream(InputStream in)

创建一个缓冲输入流并保存其参数,即输入流 in,以便从in读取数据。in:底层输入流。

2.2 API方法

所有的方法继承和重写了父类FilterInputStream方法,没有提供新的方法。

int read();  
int read(byte[] b); 
int read(byte[] b, int off, int len);
int available();   
void close();

3 案例

使用带有缓冲区的字节流,实现文件的copy。

/**
 * @author lx
 */
public class BufferedStreamCopy {

    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("C:\\Users\\lx\\Desktop\\test.wmv"));
            bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\lx\\Desktop\\test2.wmv"));
            byte[] by = new byte[1024];
            int i;
            while ((i = bis.read(by)) != -1) {
                bos.write(by, 0, i);
                bos.flush();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }

}

如有需要交流,或者文章有误,请直接留言。另外希望点赞、收藏、关注,我将不间断更新各种Java学习博客!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值