gpt4 book ai didi

java - FileOutputStream.writeBytes 越界

转载 作者:行者123 更新时间:2023-11-30 03:43:24 25 4
gpt4 key购买 nike

我的程序将文件读​​取到字节数组中,然后尝试从该文件中提取 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);

关于java - FileOutputStream.writeBytes 越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26306066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com