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

相关文章

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

Python使用Pandas对比两列数据取最大值的五种方法

《Python使用Pandas对比两列数据取最大值的五种方法》本文主要介绍使用Pandas对比两列数据取最大值的五种方法,包括使用max方法、apply方法结合lambda函数、函数、clip方法、w... 目录引言一、使用max方法二、使用apply方法结合lambda函数三、使用np.maximum函数

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满