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

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

MySQL 8 中的一个强大功能 JSON_TABLE示例详解

《MySQL8中的一个强大功能JSON_TABLE示例详解》JSON_TABLE是MySQL8中引入的一个强大功能,它允许用户将JSON数据转换为关系表格式,从而可以更方便地在SQL查询中处理J... 目录基本语法示例示例查询解释应用场景不适用场景1. ‌jsON 数据结构过于复杂或动态变化‌2. ‌性能要

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

MySQL字符串常用函数详解

《MySQL字符串常用函数详解》本文给大家介绍MySQL字符串常用函数,本文结合实例代码给大家介绍的非常详细,对大家学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql字符串常用函数一、获取二、大小写转换三、拼接四、截取五、比较、反转、替换六、去空白、填充MySQL字符串常用函数一、

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A