【问题标题】:FileOutputStream.writeBytes out of boundsFileOutputStream.writeBytes 越界
【发布时间】:2014-10-10 18:46:49
【问题描述】:

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

【问题讨论】:

标签: java indexoutofboundsexception


【解决方案1】:

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。因此,您的索引超出范围是因为您的偏移量或限制过高。我不知道你为什么选择这 2 个数字背后的含义,但你可以这样做。

 fileOuputStream.write(bFile, 1573278, bFile.length - 1573278);

【讨论】:

  • 我看到我完全想念它是如何工作的吗谢谢你为我清理它我的代码现在可以完美运行非常感谢你
猜你喜欢
  • 2014-05-31
  • 1970-01-01
  • 2012-07-19
  • 2013-10-21
  • 2012-10-28
  • 2013-12-15
  • 2017-09-30
  • 1970-01-01
相关资源
最近更新 更多