缓冲字节流BufferedOutputStream、BufferedInputStream

忘是亡心i 2022-09-10 12:19 233阅读 0赞

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

文章目录

  • 1 BufferedOutputStream缓冲区字节输出流
    • 1.1 构造器
  • 1.2 API方法
  • 2 BufferedInputStream缓冲区字节输入流
    • 2.1 构造器
    • 2.2 API方法
  • 3 案例

1 BufferedOutputStream缓冲区字节输出流

  1. public class BufferedOutputStream
  2. extends FilterOutputStream

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

1.1 构造器

  1. public BufferedOutputStream(OutputStream out)

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

1.2 API方法

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

  1. void write(int b);
  2. void write(byte[] b);
  3. void write(byte[] b, int off, int len);
  4. void flush();
  5. void close();

2 BufferedInputStream缓冲区字节输入流

  1. public class BufferedInputStream
  2. extends FilterInputStream

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

2.1 构造器

  1. public BufferedInputStream(InputStream in)

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

2.2 API方法

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

  1. int read();
  2. int read(byte[] b);
  3. int read(byte[] b, int off, int len);
  4. int available();
  5. void close();

3 案例

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

  1. /**
  2. * @author lx
  3. */
  4. public class BufferedStreamCopy {
  5. public static void main(String[] args) throws IOException {
  6. BufferedInputStream bis = null;
  7. BufferedOutputStream bos = null;
  8. try {
  9. bis = new BufferedInputStream(new FileInputStream("C:\\Users\\lx\\Desktop\\test.wmv"));
  10. bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\lx\\Desktop\\test2.wmv"));
  11. byte[] by = new byte[1024];
  12. int i;
  13. while ((i = bis.read(by)) != -1) {
  14. bos.write(by, 0, i);
  15. bos.flush();
  16. }
  17. } catch (Exception e) {
  18. System.out.println(e.toString());
  19. } finally {
  20. if (bis != null) {
  21. bis.close();
  22. }
  23. if (bos != null) {
  24. bos.close();
  25. }
  26. }
  27. }
  28. }

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

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读