FileOutputStream.writeBytes超出范围

时间:2014-10-10 18:46:49

标签: java indexoutofboundsexception

我的程序将文件读​​入字节数组,然后尝试从文件中删除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)

1 个答案:

答案 0 :(得分:2)

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);