標籤:cep new 定向 stream 寫入 讀取 數組 cte ret
定義
繼承了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,比較容易理解
問題:
無
參考:
Java I/O系列(二)ByteArrayInputStream源碼分析及理解