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

來源:互聯網
上載者:User

標籤: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源碼分析及理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.