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

相关文章

SpringBoot利用树形结构优化查询速度

《SpringBoot利用树形结构优化查询速度》这篇文章主要为大家详细介绍了SpringBoot利用树形结构优化查询速度,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一个真实的性能灾难传统方案为什么这么慢N+1查询灾难性能测试数据对比核心解决方案:一次查询 + O(n)算法解决

Go语言使用sync.Mutex实现资源加锁

《Go语言使用sync.Mutex实现资源加锁》数据共享是一把双刃剑,Go语言为我们提供了sync.Mutex,一种最基础也是最常用的加锁方式,用于保证在任意时刻只有一个goroutine能访问共享... 目录一、什么是 Mutex二、为什么需要加锁三、实战案例:并发安全的计数器1. 未加锁示例(存在竞态)

SpringBoot实现虚拟线程的方案

《SpringBoot实现虚拟线程的方案》Java19引入虚拟线程,本文就来介绍一下SpringBoot实现虚拟线程的方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录什么是虚拟线程虚拟线程和普通线程的区别SpringBoot使用虚拟线程配置@Async性能对比H

Linux中的HTTPS协议原理分析

《Linux中的HTTPS协议原理分析》文章解释了HTTPS的必要性:HTTP明文传输易被篡改和劫持,HTTPS通过非对称加密协商对称密钥、CA证书认证和混合加密机制,有效防范中间人攻击,保障通信安全... 目录一、什么是加密和解密?二、为什么需要加密?三、常见的加密方式3.1 对称加密3.2非对称加密四、

javaSE类和对象进阶用法举例详解

《javaSE类和对象进阶用法举例详解》JavaSE的面向对象编程是软件开发中的基石,它通过类和对象的概念,实现了代码的模块化、可复用性和灵活性,:本文主要介绍javaSE类和对象进阶用法的相关资... 目录前言一、封装1.访问限定符2.包2.1包的概念2.2导入包2.3自定义包2.4常见的包二、stati

MySQL中读写分离方案对比分析与选型建议

《MySQL中读写分离方案对比分析与选型建议》MySQL读写分离是提升数据库可用性和性能的常见手段,本文将围绕现实生产环境中常见的几种读写分离模式进行系统对比,希望对大家有所帮助... 目录一、问题背景介绍二、多种解决方案对比2.1 原生mysql主从复制2.2 Proxy层中间件:ProxySQL2.3

SpringBoot结合Knife4j进行API分组授权管理配置详解

《SpringBoot结合Knife4j进行API分组授权管理配置详解》在现代的微服务架构中,API文档和授权管理是不可或缺的一部分,本文将介绍如何在SpringBoot应用中集成Knife4j,并进... 目录环境准备配置 Swagger配置 Swagger OpenAPI自定义 Swagger UI 底

解决hive启动时java.net.ConnectException:拒绝连接的问题

《解决hive启动时java.net.ConnectException:拒绝连接的问题》Hadoop集群连接被拒,需检查集群是否启动、关闭防火墙/SELinux、确认安全模式退出,若问题仍存,查看日志... 目录错误发生原因解决方式1.关闭防火墙2.关闭selinux3.启动集群4.检查集群是否正常启动5.

SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南

《SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南》本文将基于开源项目springboot-easyexcel-batch进行解析与扩展,手把手教大家如何在SpringBo... 目录项目结构概览核心依赖百万级导出实战场景核心代码效果百万级导入实战场景监听器和Service(核心

idea Maven Springboot多模块项目打包时90%的问题及解决方案

《ideaMavenSpringboot多模块项目打包时90%的问题及解决方案》:本文主要介绍ideaMavenSpringboot多模块项目打包时90%的问题及解决方案,具有很好的参考价值,... 目录1. 前言2. 问题3. 解决办法4. jar 包冲突总结1. 前言之所以写这篇文章是因为在使用Mav