以下基于 Java 11 源码对 InputStream
的核心设计、关键方法实现及底层机制进行深度剖析,结合源码逐层解析其工作原理和设计思想。
一、类结构与设计定位
1. 基础定义与继承关系
public abstract class InputStream implements Closeable {
// 核心抽象方法:读取单个字节,子类必须实现
public abstract int read() throws IOException;
}
- 抽象类:无法直接实例化,需子类(如
FileInputStream
、ByteArrayInputStream
)实现read()
。 - 实现接口:
Closeable
扩展自AutoCloseable
,支持try-with-resources
自动关闭。
2. 核心字段
private static final int MAX_SKIP_BUFFER_SIZE = 2048; // skip() 最大缓冲区
private static final int DEFAULT_BUFFER_SIZE = 8192; // 默认缓冲区大小(用于 readNBytes 等)
- 优化跳过操作和批量读取的内存使用。
二、核心方法源码剖析
1. 读取操作:read()
方法族
-
单字节读取(抽象方法)
子类必须实现,返回0-255
或-1
(流结束)。public abstract int read() throws IOException;
-
批量读取(默认实现)
public int read(byte b[]) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { // 边界检查 Objects.checkFromIndexSize(off, len, b.length); if (len == 0) return 0; int c = read(); // 调用子类实现的单字节读取 if (c == -1) return -1; b[off] = (byte)c; int i = 1; t