我的程序将文件读入字节数组,然后尝试从文件中雕刻出bmp图像。问题是我遇到了界外错误。
{
public static void main( String[] args )
{
FileInputStream fileInputStream=null;
File file = new File("C:/thumbcache_32.db");
byte[] bFile = new byte[(int) file.length()];
System.out.println("Byte array size: " + file.length());
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream("C:/Users/zak/Desktop/thumb final/Carved_image.bmp");
fileOuputStream.write(bFile,1573278,1577427);
fileOuputStream.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}
}
文件加载到的字节数组的大小为“ 3145728”
我正在尝试将字节“ 1573278”复制到“ 1577427”。如您所见,这些字节在字节数组的范围内,所以不确定为什么我收到此错误
运行时程序的输出
Byte array size: 3145728
java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(Unknown Source)
at Byte_copy.main(Byte_copy.java:28)
最佳答案
FileOutputStream.write包含3个参数,最后2个是偏移量和长度。因此,假设我们有一个大小为10的数组:
byte [] arr = new byte[10];
FileOutputStream out = ...
out.write(arr, 5, 5); // writes the last 5 bytes of the file, skipping the first 5
out.write(arr, 0, 10); // writes all the bytes of the array
out.write(arr, 5, 10); // ERROR! index out of bounds,
// your attempting to write 10 bytes starting at offset 5
现在在您的代码中使用
fileOuputStream.write(bFile,1573278,1577427);
和
1573278+1577427=3150705
,如您所见3150705>3145728。因此,您的索引超出范围是因为偏移量或限制值都很高。我不知道为什么选择这两个数字的含义,但是您可以这样做。 fileOuputStream.write(bFile, 1573278, bFile.length - 1573278);