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中的getBytes()方法使用详解

《Java中的getBytes()方法使用详解》:本文主要介绍Java中getBytes()方法使用的相关资料,getBytes()方法有多个重载形式,可以根据需要指定字符集来进行转换,文中通过代... 目录前言一、常见重载形式二、示例代码三、getBytes(Charset charset)和getByt

Java使用Stream流的Lambda语法进行List转Map的操作方式

《Java使用Stream流的Lambda语法进行List转Map的操作方式》:本文主要介绍Java使用Stream流的Lambda语法进行List转Map的操作方式,具有很好的参考价值,希望对大... 目录背景Stream流的Lambda语法应用实例1、定义要操作的UserDto2、ListChina编程转成M

Spring框架中@Lazy延迟加载原理和使用详解

《Spring框架中@Lazy延迟加载原理和使用详解》:本文主要介绍Spring框架中@Lazy延迟加载原理和使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、@Lazy延迟加载原理1.延迟加载原理1.1 @Lazy三种配置方法1.2 @Component

使用easy connect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题

《使用easyconnect之后,maven无法使用,原来需要配置-Djava.net.preferIPv4Stack=true问题》:本文主要介绍使用easyconnect之后,maven无法... 目录使用easGWowCy connect之后,maven无法使用,原来需要配置-DJava.net.pr

idea报错java: 非法字符: ‘\ufeff‘的解决步骤以及说明

《idea报错java:非法字符:‘ufeff‘的解决步骤以及说明》:本文主要介绍idea报错java:非法字符:ufeff的解决步骤以及说明,文章详细解释了为什么在Java中会出现uf... 目录BOM是什么?1. BOM的作用2. 为什么会出现 \ufeff 错误?3. 如何解决 \ufeff 问题?最

python+OpenCV反投影图像的实现示例详解

《python+OpenCV反投影图像的实现示例详解》:本文主要介绍python+OpenCV反投影图像的实现示例详解,本文通过实例代码图文并茂的形式给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前言二、什么是反投影图像三、反投影图像的概念四、反向投影的工作原理一、利用反向投影backproj

使用Java编写一个字符脱敏工具类

《使用Java编写一个字符脱敏工具类》这篇文章主要为大家详细介绍了如何使用Java编写一个字符脱敏工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、字符脱敏工具类2、测试工具类3、测试结果1、字符脱敏工具类import lombok.extern.slf4j.Slf4j

Java实现按字节长度截取字符串

《Java实现按字节长度截取字符串》在Java中,由于字符串可能包含多字节字符,直接按字节长度截取可能会导致乱码或截取不准确的问题,下面我们就来看看几种按字节长度截取字符串的方法吧... 目录方法一:使用String的getBytes方法方法二:指定字符编码处理方法三:更精确的字符编码处理使用示例注意事项方

pandas DataFrame keys的使用小结

《pandasDataFramekeys的使用小结》pandas.DataFrame.keys()方法返回DataFrame的列名,类似于字典的键,本文主要介绍了pandasDataFrameke... 目录Pandas2.2 DataFrameIndexing, iterationpandas.DataF

使用Python和PaddleOCR实现图文识别的代码和步骤

《使用Python和PaddleOCR实现图文识别的代码和步骤》在当今数字化时代,图文识别技术的应用越来越广泛,如文档数字化、信息提取等,PaddleOCR是百度开源的一款强大的OCR工具包,它集成了... 目录一、引言二、环境准备2.1 安装 python2.2 安装 PaddlePaddle2.3 安装