问题描述
给定一个文件长度为 nnn,现在要求读取长度为 mmm 的内容,当 m<=nm<=nm<=n 时,只读取 mmm 个字节,当 m>nm > nm>n时,循环读取文件进行填充, 直到读取 nnn 填充满为止。
解决办法
可以利用 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;
}

被折叠的 条评论
为什么被折叠?



