Java-IO之超类InputStream

本文详细介绍了Java中的InputStream类,它是所有字节输入流类的基类。文中解释了如何使用read方法读取字节数据,skip方法跳过指定数量的字节,以及available方法查看可读取的数据量等。

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

InputStream是以字节为单位的输出流,通过以下框架图可以看到InputStream是所有以字节输入流类的公共父类:

基于JDK8的InputStream类源码:

package com.fengxiyuma.kuanjia;

import java.io.Closeable;
import java.io.IOException;

public abstract class InputStream implements Closeable {  
  
    //最大跳过的缓冲区大小  
    private static final int MAX_SKIP_BUFFER_SIZE = 2048;  
    //从输入的流中读取下一个字节  
    public abstract int read() throws IOException;  
    //从输入流中读取一定大小的字节,没有数据返回-1  
    public int read(byte b[]) throws IOException {  
        return read(b, 0, b.length);  
    }  
    //从输入流中读取的数据放到b数组中起始位置为off,长度为len  
    public int read(byte b[], int off, int len) throws IOException {  
        if (b == null) {  
            throw new NullPointerException();  
        } else if (off < 0 || len < 0 || len > b.length - off) {  
            throw new IndexOutOfBoundsException();  
        } else if (len == 0) {  
            return 0;  
        }  
  
        int c = read();  
        if (c == -1) {  
            return -1;  
        }  
        b[off] = (byte)c;  
  
        int i = 1;  
        try {  
            for (; i < len ; i++) {  
                c = read();  
                if (c == -1) {  
                    break;  
                }  
                b[off + i] = (byte)c;  
            }  
        } catch (IOException ee) {  
        }  
            return i;  
        }  
  
        //跳过输入流的长度为n字节  
        public long skip(long n) throws IOException {  
  
            long remaining = n;  
            int nr;  
  
            if (n <= 0) {  
                return 0;  
            }  
  
            int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);  
            byte[] skipBuffer = new byte[size];  
            while (remaining > 0) {  
                nr = read(skipBuffer, 0, (int)Math.min(size, remaining));  
                if (nr < 0) {  
                    break;  
                }  
                remaining -= nr;  
            }  
  
        return n - remaining;  
        }  
    //返回从输入流中可以读取的数据  
    public int available() throws IOException {  
        return 0;  
    }  
    //关闭输入流,释放任何与这个流有关的资源  
    public void close() throws IOException {}  
        //标记在这个输入流的当前位置  
    public synchronized void mark(int readlimit) {}  
        //返回到最近标记的位置  
    public synchronized void reset() throws IOException {  
        throw new IOException("mark/reset not supported");  
    }  
    //测试这个输入流是否支持标记或者重置方法  
    public boolean markSupported() {  
        return false;  
    }  
  
}  

转载:https://blog.youkuaiyun.com/qq924862077/article/details/52689867

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值