0

我尝试逐块比较两个文件。如果块相等 - 获取下一个块并比较它们。如果最终块相等 - 返回 true;所有其他变体 - 返回 false。我不明白如何正确处理下一个块以及如何获得文件结尾。

private static boolean getBlocks(File file1, File file2, int count) throws IOException {
    RandomAccessFile raf1 = new RandomAccessFile(file1, "r");
    RandomAccessFile raf2 = new RandomAccessFile(file2, "r");
    int point = count * 512;
    FileChannel fc1 = raf1.getChannel();
    FileChannel fc2 = raf2.getChannel();
    MappedByteBuffer buffer1 = fc1.map(FileChannel.MapMode.READ_ONLY, point, 512);
    MappedByteBuffer buffer2 = fc2.map(FileChannel.MapMode.READ_ONLY, point, 512);
    byte[] bytes1 = new byte[512];
    byte[] bytes2 = new byte[512];
    buffer1.get(bytes1);
    buffer2.get(bytes2);
    if (bytes1.length == bytes2.length) {
        for (int i = 0; i < bytes1.length; i++) {
            if(bytes1[i] != bytes2[i]) {
                return false;
            }
        }
        if (true) {
            count++;
            getBlocks(file1, file2, point);
        }
    }
    buffer1.clear();
    buffer2.clear();
    return true;
}
4

1 回答 1

0

这就是您可以逐字节读取文件直到达到 EOF 的方式:http ://www.java2s.com/Code/Java/File-Input-Output/Testingforendofilewhilereadingabyteatatime.htm

使用时MappedByteBuffer应该是答案:https ://stackoverflow.com/a/12509314/1321564

于 2014-11-09T11:48:10.147 回答