2014-12-02 70 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點位置的字節數組。

所以,您訪問陣列位置的邏輯是錯誤的。如錯誤行所示,您正在訪問和索引超出界限(高於限制)。

我希望我能幫助你。