2014-12-02 45 views
0

我有一个问题,用这种方法IndexOutOfBoundsException异常的字节缓冲区的比较java的

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

在结果我在while循环陷入IndexOutOfBoundsException异常。 我怎样才能解决这个问题,并通过块来比较两个文件?

+0

Err,'ByteBuffer'定义了'.equals()'那么你为什么不使用它呢? – fge 2014-12-02 19:49:54

+0

你在哪里得到什么IndexOutOfBoundsException?我没有看到任何可以产生的地方。 – zapl 2014-12-02 20:00:06

+0

哦,如果我尝试返回buffer1.equals(buffer2),我得到java.io.IOException:映射失败 – 2014-12-02 20:03:46

回答

2

是的......它必须废话。

您创建一个长度为'SIZE'的字节数组,并通过点'var'以'SIZE'vallue递增的方式访问它的位置。

例如:

int SIZE = 10; 
int point = 0;  
while(point < channel.size() - SIZE){ 
    buffer1.get(bytes1, point, SIZE); 
    // Your logic here 
    point += SIZE; 
} 

当你做到以上,SIZE vallue增量enourmously和您尝试访问与会比它的大小更高的vallue点位置的字节数组。

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

我希望我能帮助你。