[Java/字节流/BytesReader] 核心源码精讲: ByteArrayInputStream(字节数组输入流)
概述 : ByteArrayInputStream(字节数组输入流)
简介
- 字节数组输入流在内存中创建一个字节数组缓冲区,从输入流读取的数据保存在该字节数组缓冲区中。
java.io.ByteArrayInputStream
创建对象的方式
创建字节数组输入流对象有以下几种方式。
- 方式1 接收字节数组作为参数创建:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
- 方式2 接收一个字节数组,和两个整形变量 off、len,off表示第一个读取的字节,len表示读取字节的长度。
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len)
成功创建字节数组输入流对象后,可以参见以下列表中的方法,对流进行读操作或其他操作。
常用API
| 序号 | 方法描述 |
|---|---|
| 1 | public int read() 从此输入流中读取下一个数据字节。 |
| 2 | public int read(byte[] r, int off, int len) 将最多 len 个数据字节从此输入流读入字节数组。 |
| 3 | public int available() 返回可不发生阻塞地从此输入流读取的字节数。 |
| 4 | public void mark(int read) 设置流中的当前标记位置。 |
| 5 | public long skip(long n) 从此输入流中跳过 n 个输入字节。 |
示例
下面的例子演示了ByteArrayInputStream 和 ByteArrayOutputStream的使用:
import java.io.*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 ) {
// 获取用户输入值
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x= 0 ; x < b.length; x++) {
// 打印字符
System.out.print((char)b[x] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bInput = new ByteArrayInputStream(b);
System.out.println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ ) {
while(( c= bInput.read())!= -1) {
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
out
asdfghjkly
Print the content
a s d f g h j k l y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y
最佳实践
基于封装 ByteArrayInputStream 的 BytesReader
BytesReader
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Map;
/**
* 以字节数据为源的读取器
* @note 核心原理: 基于字节流工具类 {@link ByteArrayInputStream } 读取字节数据
* @updateTime 2025.6.26 13:50
*/
@Slf4j
public class BytesReader implements MySourceReader {
private ByteArrayInputStream byteArrayInputStream;
public BytesReader(byte [] bytes) {
this.byteArrayInputStream = new ByteArrayInputStream(bytes);
}
public BytesReader(byte [] bytes, int offset, int length) {
this.byteArrayInputStream = new ByteArrayInputStream(bytes, offset, length);
}
public int read(){
return this.byteArrayInputStream.read();
}
/**
* 读取1个字节
* @return
*/
public byte readByte(){
int byteSize = 1;
byte [] targetBuffer = new byte[byteSize];
int off = 0;//目标字节数组的起始位置
int readSize = read(targetBuffer, off, byteSize);
if(log.isDebugEnabled()){
log.debug("off:{}, readSize:{}", off, readSize);
}
return targetBuffer[0];
}
public Map.Entry<Integer, byte[]> readBytes(int length){
byte [] destinationBuffer = new byte[ length];
int destinationBufferOffset = 0;
int destinationBufferLength = destinationBuffer.length;
int actualLength = this.byteArrayInputStream.readNBytes(destinationBuffer, destinationBufferOffset, destinationBufferLength);
final Map.Entry<Integer, byte[]> result = new Map.Entry<Integer, byte[]>() {
@Override
public Integer getKey() {
return actualLength;
}
@Override
public byte[] getValue() {
return destinationBuffer;
}
@Override
public byte[] setValue(byte[] value) {
throw new RuntimeException("Not support set value method!");
}
};
return result;
}
/**
* 从指定的位置读取最多 length 个字节数据,并存放到 targetBuffer 中
* @param destinationBuffer 目标字节数组
* @param destinationBufferOffset 目标字节数组的起始位置 (容易理解错误,多注意)
* @param length 要读取的字节数
* @return
*/
public int read(byte destinationBuffer[], int destinationBufferOffset, int length){
return this.byteArrayInputStream.readNBytes(destinationBuffer, destinationBufferOffset, length);
}
public int read(byte destinationBuffer[], int length){
int destinationBufferOffset = 0;
return this.byteArrayInputStream.readNBytes(destinationBuffer, destinationBufferOffset, length);
}
public int read(byte destinationBuffer[]){
int destinationBufferOffset = 0;
int destinationBufferLength = destinationBuffer.length;
return this.byteArrayInputStream.readNBytes(destinationBuffer, destinationBufferOffset, destinationBufferLength);
}
public long skip(int length){
return byteArrayInputStream.skip(length);
}
/**
* 获取下一字节的位置
* @description
* 1. 利用反射原理,将 java.io.ByteArrayInputStream 的 private 属性 pos 读取出来
* 2. 不建议高频调用 (影响调用程序的性能)
* @return
*/
@SneakyThrows
public int next(){
int next = Integer.MIN_VALUE; //读取失败时,以此值为标志
//反射方法1 : Java 17 中需结合 VM Option 参数 : `--add-opens java.base/java.io=ALL-UNNAMED`
//java.lang.reflect.Field field = java.io.ByteArrayInputStream.class.getDeclaredField("pos");
//field.setAccessible(true);
//next = field.getInt( this );//读取 next 的值
////field.set(this, Integer.MIN_VALUE);//设置字段的值
//反射方法2: 基于 Unsafe
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
// 获取私有字段的偏移量
Field nextField = ByteArrayInputStream.class.getDeclaredField("pos");
long offset = unsafe.objectFieldOffset(nextField);
next = unsafe.getInt(this.byteArrayInputStream, offset);
//unsafe.putInt(byteArrayInputStream, offset, 10);// 设置字段值
return next;//next : 下标从 0 开始; 即将读取的下一个 char 的下标位置
}
public Boolean hasNext(){
return byteArrayInputStream.available() > 0;
}
}
Demo
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.Map;
@Slf4j
public class BytesReaderTest {
/**
* 读取字节数据
*/
@Test
public void readBytesTest(){
byte bytes [] = new byte [] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
BytesReader bytesReader = new BytesReader(bytes);
int offset = 0;
while (bytesReader.hasNext()) {
try {
offset = bytesReader.next();
//log.info("bytes[{}] : 0x{}", offset, BytesUtils.byteToHexString( bytesReader.readByte() ) );//每次读取1个字节
int readSize = 3;//每次读取的字节数
Map.Entry<Integer, byte[]> readResult = bytesReader.readBytes(readSize);
int actualLength = readResult.getKey();
byte [] readBytes = readResult.getValue();
log.info("bytes[offset={}] : 0x{}", offset, BytesUtils.bytesToHexString( readBytes ) );//eg: "bytes[offset=0] : 0x010203"
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
out
[2025/06/26 14:08:25.668] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=0] : 0x010203
[2025/06/26 14:08:25.676] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=3] : 0x040506
[2025/06/26 14:08:25.677] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=6] : 0x070809
[2025/06/26 14:08:25.678] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=9] : 0x101112
[2025/06/26 14:08:25.679] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=12] : 0x131415
[2025/06/26 14:08:25.680] [INFO ] [main] [com.xxx.sdk.utils.bytes.BytesReaderTest :27 readBytesTest] bytes[offset=15] : 0x160000
Y 推荐文献
- [Java/HexStringReader] 核心源码精讲:java.io.StringReader类(JDK1.1-) - 博客园/千千寰宇
- [Java SE] 基础工具类:ByteUtils(字节操作) - 博客园/千千寰宇
X 参考文献
[Java/字节流/BytesReader] 核心源码精讲: ByteArrayInputStream(字节数组输入流)的更多相关文章
- java中ReentrantLock核心源码详解
ReentrantLock简介 ReentrantLock是一个可重入且独占式的锁,它具有与使用synchronized监视器锁相同的基本行为和语义,但与synchronized关键字相比,它更灵活. ...
- 3 手写Java HashMap核心源码
手写Java HashMap核心源码 上一章手写LinkedList核心源码,本章我们来手写Java HashMap的核心源码. 我们来先了解一下HashMap的原理.HashMap 字面意思 has ...
- 手写 Java HashMap 核心源码
手写 Java HashMap 核心源码 手写 Java HashMap 核心源码 上一章手写 LinkedList 核心源码,本章我们来手写 Java HashMap 的核心源码. 我们来先了解一下 ...
- Java内存管理-掌握类加载器的核心源码和设计模式(六)
勿在流沙筑高台,出来混迟早要还的. 做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 上一篇文章介绍了类加载器分类以及类加载器的双亲委派模型,让我们能够从整体上对类加载器有 ...
- 6 手写Java LinkedHashMap 核心源码
概述 LinkedHashMap是Java中常用的数据结构之一,安卓中的LruCache缓存,底层使用的就是LinkedHashMap,LRU(Least Recently Used)算法,即最近最少 ...
- 2 手写Java LinkedList核心源码
上一章我们手写了ArrayList的核心源码,ArrayList底层是用了一个数组来保存数据,数组保存数据的优点就是查找效率高,但是删除效率特别低,最坏的情况下需要移动所有的元素.在查找需求比较重要的 ...
- 1 手写Java ArrayList核心源码
手写ArrayList核心源码 ArrayList是Java中常用的数据结构,不光有ArrayList,还有LinkedList,HashMap,LinkedHashMap,HashSet,Queue ...
- Android版数据结构与算法(五):LinkedHashMap核心源码彻底分析
版权声明:本文出自汪磊的博客,未经作者允许禁止转载. 上一篇基于哈希表实现HashMap核心源码彻底分析 分析了HashMap的源码,主要分析了扩容机制,如果感兴趣的可以去看看,扩容机制那几行最难懂的 ...
- 并发编程之 SynchronousQueue 核心源码分析
前言 SynchronousQueue 是一个普通用户不怎么常用的队列,通常在创建无界线程池(Executors.newCachedThreadPool())的时候使用,也就是那个非常危险的线程池 ^ ...
- HashMap的结构以及核心源码分析
摘要 对于Java开发人员来说,能够熟练地掌握java的集合类是必须的,本节想要跟大家共同学习一下JDK1.8中HashMap的底层实现与源码分析.HashMap是开发中使用频率最高的用于映射(键值对 ...
随机推荐
- SQL Server 中的异常处理
为什么我们需要 SQL Server 中的异常处理? 让我们通过一个示例来了解 SQL Server 中异常处理的必要性.因此,创建一个 SQL Server 存储过程,通过执行以下查询来除以两个数字 ...
- layui table表格中点击图片放大
{field:'plateNoPicUri', title: '图片' ,width:"10%" ,templet:function(data){ if("" ...
- 【U-Boot】解决U-Boot的“Unknown command 'help' - try 'help'”问题
[U-Boot]解决U-Boot的"Unknown command 'help' - try 'help'"问题 零.起因 最近在玩U-Boot,自己编译U-Boot之后输入hel ...
- 字符串匹配究极大招【KMP】:带你一步步从原理到构建
目录 前言 KMP原理 什么是前缀表 如何构建前缀表 next数组 使用next数组做匹配 实战演练 前言 一文带你了解如何去理解并实现KMP算法.本文用于记录自己的学习过程,同时向大家进行分享相关的 ...
- win7激活,2023年亲测可用 ,win7激活密钥,激活码
还在找激活密钥,激活win7吗,试了无数个都激活不了? 直接用这个工具激活吧,亲测可用,用过的都知道. WIN7Chew-WGA0.9.exe 阿里云盘:https://www.aliyundrive ...
- [笔记]image对象如何添加class
1.image对象可以添class,但不能以属性.class的方法添加,而因该把他当成一个节点 2.JS添加和删除class名 添加:节点.classList.add("类名"): ...
- Dynamic adaptation to application sizes (DATAS) GC 策略
现在大家的 .NET 程序基本都部署在如 K8S 这种容器化场景下.出于节约资源的考虑,往往我们还会限制每个实例占用的资源.不知道大家发现没有,在一些高并发的场景下,我们的程序会占用非常多的内存,内存 ...
- Java5新特性--可变参数
可变参数 public class Test01 { public static void main(String[] args) { System.out.println(add(123)); Sy ...
- RandomAccessFile、FileInputStream、MappedByteBuffer、FileChannel 区别及应用场景
RandomAccessFile.FileInputStream.MappedByteBuffer.FileChannel 比较 这些类都是Java中用于文件I/O操作的类,但各有特点和适用场景.下面 ...
- Day.js 2kb日期时间处理javascript库
Day.js 与 Moment.js 的比较 优点 体积小:Day.js 的体积仅为 2KB 左右,而 Moment.js 的体积约为 67KB. API 相似:Day.js 的 API 与 Mome ...