java io (二) InputStream

本文详细解析了Java中InputStream类的实现原理,包括其核心方法read、skip等的内部运作机制,并介绍了InputStream如何处理字节读取及跳过指定数量字节的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

InputStream源码分析

**

  • 本源码基于jdk 1.8.0_102

**

package java.io;

import java.io.Closeable;

public abstract class InputStream implements Closeable {

// 允许skip的最大字节数

private static final int MAX_SKIP_BUFFER_SIZE = 2048;

public abstract int read() throws IOException;

 //将数据读入字节数组中
public int read(byte[] arg0) throws IOException {
    return this.read(arg0, 0, arg0.length);
}

 // 第一个参数是数据要读入的数组,第二个参数是读取的起点,第三个是读取的节
 //数
public int read(byte[] arg0, int arg1, int arg2) throws IOException {
    if (arg0 == null) {
        throw new NullPointerException();
    } else if (arg1 >= 0 && arg2 >= 0 && arg2 <= arg0.length - arg1) {
        if (arg2 == 0) {
            return 0;
        } else {
            int arg3 = this.read();
            if (arg3 == -1) {
                return -1;
            } else {
                arg0[arg1] = (byte) arg3;
                int arg4 = 1;

                try {
                    while (arg4 < arg2) {
                        arg3 = this.read();

                        //如果读取的字节是-1,表示读取完毕
                        if (arg3 == -1) {
                            break;
                        }

      // arg4 是标记,每读取一次就将读取的字节放到字节数组中

                        arg0[arg1 + arg4] = (byte) arg3;
                        ++arg4;
                    }
                } catch (IOException arg6) {
                    ;
                }

                return arg4;
            }
        }
    } else {
        throw new IndexOutOfBoundsException();
    }
}
 // 跳过输入流中的n个字节

public long skip(long arg0) throws IOException {
    long arg2 = arg0;
    if (arg0 <= 0L) {
        return 0L;
    } else {

        int arg5 = (int) Math.min(2048L, arg0);
          // arg4 是已经读取的字节数
        int arg4;

         for (byte[] arg6 = new byte[arg5]; arg2 > 0L; arg2 -= (long) arg4) {
            arg4 = this.read(arg6, 0, (int) Math.min((long) arg5, arg2));
            if (arg4 < 0) {
                break;
            }
        }
          // 正常退出会返回arg0,即传入的要跳过的字节数
        return arg0 - arg2;
    }
}

public int available() throws IOException {
    return 0;
}

public void close() throws IOException {
}

public synchronized void mark(int arg0) {
}

public synchronized void reset() throws IOException {
    throw new IOException("mark/reset not supported");
}

 //是否支持标记

public boolean markSupported() {
    return false;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值