基於java的InputStream.read(byte[] b,int off,int len)演算法學習
public int read(byte[] b, int off, int len) throws IOException
-
將輸入資料流中最多
len 個資料位元組讀入位元組數組。嘗試讀取多達 len 位元組,但可能讀取較少數量。以整數形式返回實際讀取的位元組數。
在輸入資料可用、檢測到流的末尾或者拋出異常前,此方法一直阻塞。
如果 b 為 null,則拋出 NullPointerException。
如果 off 為負,或 len 為負,或 off+len 大於數組 b 的長度,則拋出 IndexOutOfBoundsException。
如果 len 為 0,則沒有位元組可讀且返回 0;否則,要嘗試讀取至少一個位元組。如果因為流位於檔案末尾而沒有可用的位元組,則傳回值 -1;否則,至少可以讀取一個位元組並將其儲存在 b 中。
將讀取的第一個位元組儲存在元素 b[off] 中,下一個儲存在 b[off+1] 中,依次類推。讀取的位元組數最多等於 len。讓 k 為實際讀取的位元組數;這些位元組將儲存在元素 b[off] 至 b[off+k-1] 之間,其餘元素 b[off+k] 至 b[off+len-1] 不受影響。
在任何情況下,元素 b[0] 至 b[off] 和元素 b[off+len] 至 b[b.length-1] 都不會受到影響。
如果不是因為流位於檔案末尾而無法讀取第一個位元組,則拋出 IOException。特別是,如果輸入資料流已關閉,則拋出 IOException。
類 InputStream 的 read(b, off, len) 方法只重複調用方法 read()。如果第一個這樣的調用導致 IOException,則從對 read(b, off, len) 方法的調用中返回該異常。如果對 read() 的任何後續調用導致 IOException,則該異常會被捕獲並將發生異常時的位置視為檔案的末尾;到達該點時讀取的位元組儲存在 b 中並返回傳生異常之前讀取的位元組數。建議讓子類提供此方法的更有效實現。
-
-
參數:
-
b - 讀入資料的緩衝區。
-
off - 在其處寫入資料的數組 b 的初始位移量。
-
len - 要讀取的最大位元組數。
-
返回:
-
讀入緩衝區的總位元組數,如果由於已到達流末尾而不再有資料,則返回
-1。
-
拋出:
-
IOException - 如果發生 I/O 錯誤。
-
NullPointerException - 如果 b 為 null。
read是一個很好的讀取器,對流,如應用於下載中是一個不錯的演算法!例子:
public static final int INITIAL_SIZE = 100000;
private byte buffer[] = new byte[INITIAL_SIZE];
private int index = 0;
private int capacity() {
return (buffer.length - index);
}
public void read(InputStream in, int max) throws IOException {
long k= 0;
do {
int size;
// only read up to the max size, if the max size was
// specified
if (max != -1) {
size = Math.min(capacity(), max);
} else {
size = capacity();
}
// actually read the block
k= in.read(buffer, index, capacity());
// quit if we hit EOF
if (k< 0) {
break;
}
// adjust capacity if needed
index += k;
if (capacity() < 10) {
expand();
}
// see if we hit the max length
if (max != -1) {
max -= l;
if (max <= 0) {
break;
}
}
} while (k!= 0);
}
演算法