[英]Why am I getting ArrayIndexOutOfBoundsException in this Java program?
In Java, I am doing some work with RandomAccessFile. 在Java中,我正在使用RandomAccessFile做一些工作。 I have a file that is 8192 bytes, or 8kb.
我有一个8192字节,或8kb的文件。
The following is causing an ArrayIndexOutOfBoundsException: 以下导致ArrayIndexOutOfBoundsException:
File file = new File("TestFile1");
raf = new RandomAccessFile(file, "rw");
byte[] temp = new byte[4096];
raf.read(temp, 4096, 4096);
Even something like this causes the same error: 即使是这样的事情也会导致同样的错误:
raf.read(temp, 4096, 1);
Though something like this works perfectly: 虽然这样的东西很完美:
raf.read(temp, 0, 4096);
When I run the following, I get 8192, which is why I am confused as to why this is not working: 当我运行以下内容时,我得到8192,这就是为什么我对为什么这不起作用感到困惑:
System.out.println(raf.getChannel().size());
Why am I getting an out of bounds error if I try to read from the second half of the file? 如果尝试从文件的后半部分读取,为什么会出现超出范围的错误?
Instead of: 代替:
raf.getBytes(temp,4096,4096);
it sounds like you want: 听起来像你想要的:
raf.seek(4096); raf.getBytes(temp,0,4096);
The second parameter of getBytes
gives the offset into the buffer into which the content will be read, not the offset into the file. getBytes
的第二个参数提供将要读取内容的缓冲区的偏移量,而不是文件中的偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.