zoukankan      html  css  js  c++  java
  • java.io.ByteArrayInputStream 源码分析

    ByteArrayInputStream 包含一个内部缓冲区,该缓冲区包含从流中读取的字节。

    成员变量

        //由该流的创建者提供的 byte 数组。
        protected byte buf[];
    
        //要从输入流缓冲区中读取的下一个字符的索引。
        protected int pos;
    
        //流中当前的标记位置。
        protected int mark = 0;
    
        //比输入流缓冲区中最后一个有效字符的索引大一的索引。
        protected int count;

    构造参数 提供一个byte数组

        public ByteArrayInputStream(byte buf[]) {
            this.buf = buf;
            this.pos = 0;
            this.count = buf.length;
        }

    构造参数 

    buf - 输入缓冲区。

    offset - 缓冲区中要读取的第一个字节的偏移量。

    length - 从缓冲区中读取的最大字节数。

        public ByteArrayInputStream(byte buf[], int offset, int length) {
            this.buf = buf;
            this.pos = offset;
            this.count = Math.min(offset + length, buf.length);
            this.mark = offset;
        }

    读取一个字节

      public synchronized int read() {
            return (pos < count) ? (buf[pos++] & 0xff) : -1;
        }

    读取多个字节

        public synchronized int read(byte b[], int off, int len) {
            if (b == null) {
                throw new NullPointerException();
            } else if (off < 0 || len < 0 || len > b.length - off) {
                throw new IndexOutOfBoundsException();
            }
            //已经读完
            if (pos >= count) {
                return -1;
            }
            //判断len的大小是否超过缓冲区剩余可读字节
            int avail = count - pos;
            if (len > avail) {
                //将len设置为最后可读全部字节大小
                len = avail;
            }
            if (len <= 0) {
                return 0;
            }
            System.arraycopy(buf, pos, b, off, len);
            pos += len;
            return len;
        }

    跳过N个字节

        public synchronized long skip(long n) {
            long k = count - pos;
            if (n < k) {
                k = n < 0 ? 0 : n;
            }
    
            pos += k;
            return k;
        }

    返回可从此输入流读取(或跳过)的剩余字节数。

        public synchronized int available() {
            return count - pos;
        }

    设置mark与reset

        public void mark(int readAheadLimit) {
            mark = pos;
        }
    
        public synchronized void reset() {
            pos = mark;
        }
  • 相关阅读:
    python对于相同值的内存管理
    python的in,is和id函数
    sublime text3格式化json,格式化sql代码
    VMware15.5版本安装CentOS7
    VMware15.5版本安装Windows_Server_2008_R2
    MySQL事务
    判定表组成法
    正交试验设计
    因果图法
    错误推测法
  • 原文地址:https://www.cnblogs.com/daxin/p/3772931.html
Copyright © 2011-2022 走看看