Java I/O系列(二)ByteArrayInputStream源码分析及理解

定义


 继承了InputStream,数据源是内置的byte数组buf,那read ()方法的使命(读取一个个字节出来),在ByteArrayInputStream就是简单的通过定向的取buf元素实现的

核心源码理解


源码:

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

理解:

1. 构造ByteArrayInputStream, 直接将外部的byte数组作为内置的buf,作为被读取的数据源

源码:

 1     // 存放数据的地方
 2     protected byte buf[];
 3 
 4     // 下一个要被读取的位置,即等待读取的位置
 5     protected int pos;
 6 
 7     // 标记pos的位置
 8     protected int mark = 0;
 9 
10     // 实际能被读取的byte的数量
11     protected int count;

理解:

源码:

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

理解:

1. 该方法是被synchronized修饰的,其它方法也是,故ByteArrayInputStream是线程安全的

2. byte类型和0xff做与运算,转成byte的无符号类型(0-255),上节也说明过

源码:

 1 public synchronized int read(byte b[], int off, int len) {
 2         if (b == null) {
 3             throw new NullPointerException();
 4         } else if (off < 0 || len < 0 || len > b.length - off) {
 5             throw new IndexOutOfBoundsException();
 6         }
 7 
 8         if (pos >= count) {
 9             return -1;
10         }
11 
12         int avail = count - pos;
13         if (len > avail) {
14             len = avail;
15         }
16         if (len <= 0) {
17             return 0;
18         }
19         System.arraycopy(buf, pos, b, off, len);
20         pos += len;
21         return len;
22     }

理解:

  1. 因为数据源是byte数组,目的源也是byte数组,故直接采用了数组copy的方法,写入到b数组中

源码:

1 public synchronized long skip(long n) {
2         long k = count - pos;
3         if (n < k) {
4             k = n < 0 ? 0 : n;
5         }
6 
7         pos += k;
8         return k;
9     }

理解:

  1. 通过调整pos的值,来实现skip操作

总结:


1. 实现了mark与reset方法,mark方法中让mark=pos,reset时让pos=mark,比较容易理解

问题:


 

参考:


猜你喜欢

转载自www.cnblogs.com/nolan4954/p/9265170.html