当前位置:网站首页>ByteArrayInputStream class source code analysis
ByteArrayInputStream class source code analysis
2022-07-30 18:01:00 【51CTO】
这是 《水煮 JDK 源码》系列 的第3篇文章,计划撰写100篇关于JDK源码相关的文章
ByteArrayInputStream 类位于 java.io 包下,继承于 InputStream 类,Represents a byte array input stream,It creates a byte array buffer in memory,Then save all the data read from the input stream in the buffer,其 UML 类图如下:

1、成员变量
在 ByteArrayInputStream 中定义了4个成员变量,如下:
2、构造方法
创建 ByteArrayInputStream There are two main ways to input stream of byte array:
3、读取字节方法
ByteArrayInputStream Two methods for reading bytes are provided,如下:
上面的两个 read() 方法都使用了 synchronized 关键字,That is, it is represented as a synchronous method,It can be seen from the specific implementation,ByteArrayInputStream The data in can not be read repeatedly,Each read a byte of data,The index of the next readable byte position is automatic+1,If the last element of the byte array has been read,can no longer be read.
4、其他方法
ByteArrayInputStream The class provides some other methods,如下:
public synchronized long skip(long n):Skip from the input stream n 个字节;public synchronized int available():Gets the length in bytes that can also be read from the input stream;public boolean markSupported():Determines whether the input stream supports the tagging function,默认返回 true,即ByteArrayInputStream是支持的;public void mark(int readAheadLimit):Sets the marker position in the input stream to the current readable position;public synchronized void reset():Resets the next readable position in the input stream to the marked position;public void close():关闭输入流;
下面分别看看这些方法的具体实现.
和 ByteArrayOutputStream 一样,ByteArrayInputStream 类中的 close() methods are also implemented without any code,即使被调用,也没有任何的作用.
5、示例代码
5.1 Simple data read
上面分析了 ByteArrayInputStream 类的相关源码,Let's take a look at it with a simple example ByteArrayInputStream 该如何使用.
运行后,输出的结果如下:
5.2 验证不可重复读
Let's verify that the input stream cannot be read repeatedly.
运行后,输出结果如下:
5.3 Repeatable read implementation
从上面的结果可以看出,第2次读取时,未读取到任何数据,If you want to be able to read again,那么又该如何处理呢?可以在第1after reading,使用 reset() 方法进行重置.
运行后输出结果如下:
边栏推荐
猜你喜欢
随机推荐
图解LeetCode——11. 盛最多水的容器(难度:中等)
编曲软件FL Studio中文版安装教程及切换语言教程
【HarmonyOS】【FAQ】鸿蒙问题合集3
信息学奥赛一本通 1915:【01NOIP普及组】最大公约数与最小公倍数 | 洛谷 P1029 [NOIP2001 普及组] 最大公约数和最小公倍数问题
宽带射频放大器OA4SMM4(1)
【HMS core】【FAQ】HMS Toolkit典型问题合集1
un7.30:linux——如何在docker容器中安装MySQL?
Microsoft Office 2019 software download and installation detailed tutorial!
软件测试13年从业经验的前辈,总结的5条测试就业建议....
沃尔沃中国的年中总结,在“安全感”中寻找未来
论文阅读之《Quasi-Unsupervised Color Constancy 》
LayaBox---TypeScript---枚举
记者卧底
Metaverse Web 3.0 和 DeFi大师班
2022鹏城杯web
Prometheus 基本概念
LayaBox---TypeScript---变量声明
一个 15 年 SAP ABAP 开发人员分享的 SAPGUI 一些个性化设置和实用小技巧试读版
数据库系统原理与应用教程(067)—— MySQL 练习题:操作题 82-89(十一):数据的增、删、改操作
C陷阱与缺陷 第7章 可移植性缺陷 7.4 字符是有符号数还是无符号数









