ByteBuffer中的IndexOutOfBoundsException';s比较java

ByteBuffer中的IndexOutOfBoundsException';s比较java,java,indexoutofboundsexception,bytebuffer,Java,Indexoutofboundsexception,Bytebuffer,我对这种方法有意见 private static boolean getBlocks(File file1, File file2) throws IOException { FileChannel channel1 = new FileInputStream(file1).getChannel(); FileChannel channel2 = new FileInputStream(file2).getChannel(); int SIZE = (int) Math.

我对这种方法有意见

private static boolean getBlocks(File file1, File file2) throws IOException {
    FileChannel channel1 = new FileInputStream(file1).getChannel();
    FileChannel channel2 = new FileInputStream(file2).getChannel();
    int SIZE = (int) Math.min((8192), channel1.size());
    int point = 0;
    MappedByteBuffer buffer1 = channel1.map(FileChannel.MapMode.READ_ONLY, 0, channel1.size());
    MappedByteBuffer buffer2 = channel2.map(FileChannel.MapMode.READ_ONLY, 0, channel2.size());
    byte [] bytes1 = new byte[SIZE];
    byte [] bytes2 = new byte[SIZE];
    while (point < channel1.size() - SIZE) {
        buffer1.get(bytes1, point, SIZE);
        buffer2.get(bytes2, point, SIZE);
        if (!compareBlocks(bytes1, bytes2)) {
            return false;
        }
        point += SIZE;
    }
    return true;
}

private static boolean compareBlocks (byte[] bytes1, byte[] bytes2) {
    for (int i = 0; i < bytes1.length; i++) {
        if (bytes1[i] != bytes2[i]) {
            return false;
        }
    }
    return true;
}
private静态布尔getBlocks(文件file1、文件file2)引发IOException{
FileChannel channel1=新的FileInputStream(file1.getChannel();
FileChannel channel2=新的FileInputStream(file2.getChannel();
int SIZE=(int)Math.min((8192),channel1.SIZE());
int点=0;
MappedByteBuffer buffer1=channel1.map(FileChannel.MapMode.READ_ONLY,0,channel1.size());
MappedByteBuffer buffer2=channel2.map(FileChannel.MapMode.READ_ONLY,0,channel2.size());
字节[]字节1=新字节[大小];
byte[]bytes2=新字节[大小];
而(点
结果,我在while循环中捕获了IndexOutOfBoundsException。
我怎样才能绕过这个问题,按块比较两个文件?

是的。。。一定是废话

创建一个长度为“SIZE”的字节数组,并使用点变量访问其位置,该点变量随“SIZE”值递增

例如:

int SIZE = 10; 
int point = 0;     
while( point < channel.size() - SIZE ){
   buffer1.get(bytes1, point, SIZE);
   // Your logic here
   point += SIZE;
}
int SIZE=10;
int点=0;
同时(点
当您执行上述操作时,SIZE vallue的增量非常大,您尝试使用point position访问字节数组,它的值将高于其SIZE

因此,访问阵列位置的逻辑是错误的。正如错误行所示,您正在访问和索引超出范围(高于限制)


我希望我能帮助你。

呃,
ByteBuffer
定义了
.equals()
那么你为什么不直接使用它呢?你得到了什么?我看不到任何地方可以产生一个。哦,如果我尝试返回buffer1.equals(buffer2),我会在线程“main”java.lang.IndexOutOfBoundsException中得到java.io.IOException:Map failedException——在java.nio.Buffer.checkBounds(Buffer.java:567)——在java.nio.DirectByteBuffer.get(DirectByteBuffer.java:265)——而不是在buffer1.get(字节1、点、大小);