我必须读取一个文件,在每次迭代中我都必须从文件中读取 8 个字节。例如,在第一次迭代中,我将读取前 8 个字节,在第二次迭代中,我将读取接下来的 8 个字节,依此类推。这在 Java 中如何实现?
public static byte[] toByteArray(File file) {
long length = file.length();
byte[] array = new byte[length];
InputStream in = new FileInputStream(file);
long offset = 0;
while (offset < length) {
int count = in.read(array, offset, (length - offset));
offset += length;
}
in.close();
return array;
}
我找到了这个,但我认为这段代码正在做的是完全读取文件并制作文件数据的字节数组。但是我只需要在一次迭代中准备好我需要的那么多字节。
最佳答案
使用 DataInput对于这种类型的处理:
private void process(File file) throws IOException {
try (RandomAccessFile data = new RandomAccessFile(file, "r")) {
byte[] eight = new byte[8];
for (long i = 0, len = data.length() / 8; i < len; i++) {
data.readFully(eight);
// do something with the 8 bytes
}
}
}
我用过 RandomAccessFile但是一个DataInputStream是一个常见的选择。
关于java - 如何在JAVA中循环读取文件中固定数量的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811608/