【1.JDK底层源码剖析】1.1 InputStream核心源码剖析

以下基于 Java 11 源码InputStream 的核心设计、关键方法实现及底层机制进行深度剖析,结合源码逐层解析其工作原理和设计思想。


一、类结构与设计定位

1. 基础定义与继承关系
public abstract class InputStream implements Closeable {
   
   
    // 核心抽象方法:读取单个字节,子类必须实现
    public abstract int read() throws IOException;
}
  • 抽象类:无法直接实例化,需子类(如 FileInputStreamByteArrayInputStream)实现 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值