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

2024-01-05 06:58

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

1 使用方法

  ByteArrayInputStream 包含一个内部缓冲区,该缓冲区包含从流中读取的字节。内部计数器跟踪 read 方法要提供的下一个字节。ByteArrayOutputStream实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray()和 toString()获取数据。

1.1 方法介绍

  ByteArrayOutputStream提供的API如下:

// 构造函数ByteArrayOutputStream()ByteArrayOutputStream(int size)void    close() //关闭字节流synchronized void    reset() //重置计数器int     size() //获取当前计数synchronized byte[]  toByteArray() //将字节流转换为字节数组String  toString(int hibyte) //将字节流转换为StringString  toString(String charsetName)String  toString()synchronized void    write(byte[] buffer, int offset, int len) //写入字节数组buffer到字节流, offset是buffer的起始位置synchronized void    write(int oneByte) //写入一个字节到字节流synchronized void    writeTo(OutputStream out) //写输出流到其他输出流out
}

1.2 使用示例

public void testByteArrayOutputStream() {byte [] letter = {'h', 'i', 'j', 'k'};//新建字节流ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//写入abcdefgint i = 'a'; //awhile (i < 'h') {outputStream.write(i);i++;}System.out.println("当前字节流中的内容有: " + outputStream.toString());//写入多个outputStream.write(letter, 1, 3);System.out.println("写入letter数组中的第2,3,4个字母字节流中的内容有: " + outputStream.toString());System.out.println("当前output字节流中的字节数为: " + outputStream.size());byte [] byteArr = outputStream.toByteArray();i = 0;System.out.print("byte数组内容为: ");while (i < byteArr.length) {System.out.print(byteArr[i++] + " ");}System.out.println();OutputStream cloneOut = new ByteArrayOutputStream();try {outputStream.writeTo(cloneOut);System.out.println("cloneOut的内容为: " + cloneOut.toString());} catch (IOException e) {e.printStackTrace();}}

  运行结果如下:

当前字节流中的内容有: abcdefg
写入letter数组中的第2,3,4个字母字节流中的内容有: abcdefgijk
当前output字节流中的字节数为: 10
byte数组内容为: 97 98 99 100 101 102 103 105 106 107
cloneOut的内容为: abcdefgijk

2 源码分析

2.1构造函数

  ByteArrayOutputStream有两个构造函数,区别是初始大小不同。

/*** Creates a new byte array output stream. The buffer capacity is* initially 32 bytes, though its size increases if necessary.*/
public ByteArrayOutputStream() {this(32);
}/*** Creates a new byte array output stream, with a buffer capacity of* the specified size, in bytes.** @param   size   the initial size.* @exception  IllegalArgumentException if size is negative.*/
public ByteArrayOutputStream(int size) {if (size < 0) {throw new IllegalArgumentException("Negative initial size: "+ size);}buf = new byte[size];
}

2.2 write方法

/*** Writes the specified byte to this byte array output stream.** @param   b   the byte to be written.*/
public synchronized void write(int b) {ensureCapacity(count + 1); //增加容量, 容量不够则加倍buf[count] = (byte) b; //写入字节count += 1;
}/*** Writes <code>len</code> bytes from the specified byte array* starting at offset <code>off</code> to this byte array output stream.** @param   b     the data.* @param   off   the start offset in the data.* @param   len   the number of bytes to write.*/
public synchronized void write(byte b[], int off, int len) {if ((off < 0) || (off > b.length) || (len < 0) ||((off + len) - b.length > 0)) {throw new IndexOutOfBoundsException();}ensureCapacity(count + len); //增加容量,容量不够则加倍System.arraycopy(b, off, buf, count, len); //写入字节数组count += len;
}

2.3 writeTo方法

/*** Writes the complete contents of this byte array output stream to* the specified output stream argument, as if by calling the output* stream's write method using <code>out.write(buf, 0, count)</code>.** @param      out   the output stream to which to write the data.* @exception  IOException  if an I/O error occurs.*/
public synchronized void writeTo(OutputStream out) throws IOException {out.write(buf, 0, count); //将 当前OutputStream的buf中内容写到out中
}

2.4 toString , toByteArray方法


/*** Creates a newly allocated byte array. Its size is the current* size of this output stream and the valid contents of the buffer* have been copied into it.** @return  the current contents of this output stream, as a byte array.* @see     java.io.ByteArrayOutputStream#size()*/
public synchronized byte toByteArray()[] {return Arrays.copyOf(buf, count); //返回信得数组
}/*** Converts the buffer's contents into a string decoding bytes using the* platform's default character set. The length of the new <tt>String</tt>* is a function of the character set, and hence may not be equal to the* size of the buffer.** <p> This method always replaces malformed-input and unmappable-character* sequences with the default replacement string for the platform's* default character set. The {@linkplain java.nio.charset.CharsetDecoder}* class should be used when more control over the decoding process is* required.** @return String decoded from the buffer's contents.* @since  JDK1.1*/
public synchronized String toString() {return new String(buf, 0, count); //返回String对象
}

参考:

[1] http://www.cnblogs.com/skywang12345/p/io_02.html
[2] http://www.cnblogs.com/skywang12345/p/io_03.html
[3] http://blog.csdn.net/rcoder/article/details/6118313

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



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

相关文章

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基