問題描述
給定一個文件長度爲 ,現在要求讀取長度爲 的內容,當 時,只讀取 個字節,當 時,循環讀取文件進行填充, 直到讀取 填充滿爲止。
解決辦法
可以利用 FileInputStream
的 read(byte[], start, length)
方法來解決,因爲這個函數返回讀取到的數據長度。實現代碼如下所示。
public static byte[] readBytes(String file, int maxsize) throws Exception {
byte[] bts = new byte[maxsize];
FileInputStream fs = new FileInputStream(file);
int left = maxsize, p = 0;
while (left > 0) {
p += fs.read(bts, maxsize - left, left);
left -= p;
}
fs.close();
return bts;
}