「这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战」。
前言
大家好,我是程序猿小白 gw_Gw,很高兴能和大家一起学习进步。
以下内容部分来自于网络,如有侵权,请联系我删除,本文仅用于学习交流,不用作任何商业用途。
摘要
本文主要介绍BufferedOutputStream字节缓冲流的基本概念和使用。
欢迎关注专栏IO流学习了解更多IO流。
BufferedOutputStream使用字节缓冲流写入文件
1.1 什么是BufferedOutputStream
FilterOutputStream的子类,加强版的字节输出流。
1.2 BufferedOutputStream的构造方法
【构造方法】
BufferedOutputStream(OutputStream out)
创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
BufferedOutputStream(OutputStream out, int size)
创建一个新的缓冲输出流,以将具有指定缓冲区大小的数据写入指定的底层输出流。
参数为OutputStream类对象,我们可以使用其子类FileOutputStream对象来作为参数。如下:
【实例展示】
String path = "FileDemo\src\main\java\FileDemo\1.txt";
File file=new File(path);
//使用默认缓冲区大小8192
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//使用指定缓冲区大小
BufferedOutputStream bos1 = new BufferedOutputStream(new FileOutputStream(file),1024);
1.3 BufferedOutputStream的常用方法
常用方法就是write方法,flush方法以及close方法。
void flush()
刷新此缓冲的输出流。
void write(byte[] b)
将 b.length 个字节写入此输出流。
void write(byte[] b, int off, int len)
将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。
void write(int b)
将指定的字节写入此缓冲的输出流。
void close()
关闭此输出流并释放与此流有关的所有系统资源。
flush和close方法就不再多说,如果有不了解的,欢迎关注专栏(点击开头的穿送们即可),这里直接来看write方法。
以字节方式写入。
【实例展示】
byte[] b = new byte[1024];
//写入一个字节
bos.write(99);
//写入一个字节数组
bos.write(b);
//写入字节数组的一部分
bos.write(b,0,32);
//将缓冲区中的数据写入文件
bos.flush();
//调用flush方法并关闭资源。
bos.close();
1.4 BufferedOutputStream小结
BufferedOutputStream使用步骤:
- 创建BufferedOutputStream流对象。参数是OutputStream对象,可以使用FileOutputStream类。
- 使用write方法写入数据。
- 使用flush把缓冲区的数据写入文件中。
- 使用close方法关闭流资源。
小结
以上就是关于BufferedOutputStream字节缓冲流的方法的一些介绍,希望对读者有所帮助,如有不正之处,欢迎留言指正。