Usa*_*war 5 java file-io file filereader
我必须阅读一个文件,其中在每次迭代中我必须从文件中读取 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;
}
Run Code Online (Sandbox Code Playgroud)
我发现了这一点,但我认为这段代码所做的完全是读取文件并制作文件数据的字节数组。但是我只需要准备一次迭代中需要的字节数。
您可以轻松地根据您的需求调整代码:添加偏移量和计数,然后调用skip以获取初始N字节,如下所示 -
public static byte[] toByteArray(File file, long start, long count) {
long length = file.length();
if (start >= length) return new byte[0];
count = Math.min(count, length - start);
byte[] array = new byte[count];
InputStream in = new FileInputStream(file);
in.skip(start);
long offset = 0;
while (offset < count) {
int tmp = in.read(array, offset, (length - offset));
offset += tmp;
}
in.close();
return array;
}
Run Code Online (Sandbox Code Playgroud)