我找到了这段代码,以便将文件编码为 Base64。它正在使用偏移量。
File filePath = new File("/sdcard/videooutput.mp4");
try{
FileInputStream fin=new FileInputStream(filePath);
long length = filePath.length();
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset<bytes.length && (numRead=fin.read(bytes, offset, bytes.length-offset))>=0){
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+filePath.getName());
}
Base64.encodeToString(bytes, Base64.DEFAULT);
我不明白这段代码是 while (offset < bytes.length && (numRead=fin.read(bytes, offset, bytes.length-offset)) >= 0)
。
谁能解释一下这段代码的用途吗?我只理解它检查偏移量是否小于字节长度,其余的我不确定。
我的下一个问题是,使用偏移量对文件进行编码的原因是什么?
有关此问题的任何答案都会非常有帮助。很抱歉问这种类型的问题,但我真的需要理解这段代码。
最佳答案
int numRead=fin.read(bytes, offset, bytes.length-offset)
read 从给定的偏移量开始填充给定的字节数组,填充给定的字节数。但是,即使您请求 100 个字节,也不能保证您一定会得到它们。所以这段代码基本上是在每次调用 read() 后增加偏移量。
初始调用将尝试完全填充 byte[]。如果失败,它会将偏移量向前移动已成功复制的字节数,并尝试从新偏移量开始填充 byte[]。每次新的尝试,它只会尝试读取足够的内容来填充缓冲区中剩余的内容。
关于java - 关于在读取调用中使用偏移量的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774162/