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

相关文章

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件