Java IO:BufferedOutputStream使用详解及源码分析

2024-01-05 06:58

本文主要是介绍Java IO:BufferedOutputStream使用详解及源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用方法

  BufferedOutputStream继承于FilterOutputStream,提供缓冲输出流功能。缓冲输出流相对于普通输出流的优势是,它提供了一个缓冲数组,只有缓冲数组满了或者手动flush时才会向磁盘写数据,避免频繁IO。核心思想是,提供一个缓冲数组,写入时首先操作缓冲数组。

方法介绍

  BufferedOutputStream提供的API如下:

//构造函数
BufferedOutputStream(OutputStream out) //默认缓冲数组大小为8192
BufferedOutputStream(OutputStream out, int size)synchronized void     close() //关闭
synchronized void     flush() //刷盘
synchronized void     write(byte[] b, int off, int len) //向输出流写数据
synchronized void     write(int b)

使用示例

public void testBufferedOutput() {try {final byte [] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n'};/**创建文件输出流out,缓冲区大小为8*/OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("buff.txt")), 8);/*将letters前6个字符写入到输出流*/out.write(letters, 0 ,6);/*此时不会写入任何数据到磁盘文件*/readFile();/*继续写入4个字符*/for (int i = 0; i < 4; i++) {out.write('g' + i);}/*此时只会写入8个字符到磁盘文件*/readFile();/*此时会把所有内容写入磁盘文件*/out.flush();readFile();} catch (Exception e) {e.printStackTrace();}
}private void readFile() {try {InputStream in = new FileInputStream("buff.txt");byte [] bytes = new byte[20];in.read(bytes, 0, bytes.length);System.out.println("文件中的内容为: "  + new String(bytes));} catch (Exception e) {e.printStackTrace();}
}

  运行结果如下:

文件中的内容为:
文件中的内容为: abcdefgh
文件中的内容为: abcdefghij

源码分析

构造方法

  BufferedOutputStream的构造方法有两个,区别是字节缓冲数组大小。

/*** Creates a new buffered output stream to write data to the* specified underlying output stream.** @param   out   the underlying output stream.*/
public BufferedOutputStream(OutputStream out) {this(out, 8192);
}/*** Creates a new buffered output stream to write data to the* specified underlying output stream with the specified buffer* size.** @param   out    the underlying output stream.* @param   size   the buffer size.* @exception IllegalArgumentException if size &lt;= 0.*/
public BufferedOutputStream(OutputStream out, int size) {super(out);if (size <= 0) {throw new IllegalArgumentException("Buffer size <= 0");}buf = new byte[size];
}

write方法

  write方法有两个重载方法,分别是协议一个字节的write(int b)和写入一个字节数组的write(byte b[], int off, int len)。下面分析第二个方法的源码。

/*** Writes <code>len</code> bytes from the specified byte array* starting at offset <code>off</code> to this buffered output stream.** <p> Ordinarily this method stores bytes from the given array into this* stream's buffer, flushing the buffer to the underlying output stream as* needed.  If the requested length is at least as large as this stream's* buffer, however, then this method will flush the buffer and write the* bytes directly to the underlying output stream.  Thus redundant* <code>BufferedOutputStream</code>s will not copy data unnecessarily.** @param      b     the data.* @param      off   the start offset in the data.* @param      len   the number of bytes to write.* @exception  IOException  if an I/O error occurs.*/
public synchronized void write(byte b[], int off, int len) throws IOException {if (len >= buf.length) { //如果写入长度比buf长度长,直接写入文件,不走缓冲区/* If the request length exceeds the size of the output buffer,flush the output buffer and then write the data directly.In this way buffered streams will cascade harmlessly. */flushBuffer(); //将原有缓冲区内容刷盘out.write(b, off, len); //直接写入文件return;}if (len > buf.length - count) { //可用空间不足,先刷盘flushBuffer();}System.arraycopy(b, off, buf, count, len); //复制写入count += len;
}
/** Flush the internal buffer */
private void flushBuffer() throws IOException {if (count > 0) {out.write(buf, 0, count);count = 0;}
}

flush方法

/*** Flushes this buffered output stream. This forces any buffered* output bytes to be written out to the underlying output stream.** @exception  IOException  if an I/O error occurs.* @see        java.io.FilterOutputStream#out*/
public synchronized void flush() throws IOException {flushBuffer(); //刷盘out.flush(); //未做任何实现
}

参考:

[1] http://www.cnblogs.com/skywang12345/p/io_13.html
[2] http://czj4451.iteye.com/blog/1545159

这篇关于Java IO:BufferedOutputStream使用详解及源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/572032

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF