Changes between Version 5 and Version 6 of HashSourceCodes


Ignore:
Timestamp:
Nov 28, 2008, 6:26:46 PM (15 years ago)
Author:
guest
Comment:

better exception handling

Legend:

Unmodified
Added
Removed
Modified
  • HashSourceCodes

    v5 v6  
    116116{{{
    117117#!java
    118 import java.io.File;
    119 import java.io.FileInputStream;
    120 import java.io.IOException;
    121 import java.nio.ByteOrder;
    122 import java.nio.LongBuffer;
    123 import java.nio.MappedByteBuffer;
    124 import java.nio.channels.FileChannel;
    125 import java.nio.channels.FileChannel.MapMode;
    126 
    127 
    128118/**
    129119 * Hash code is based on Media Player Classic. In natural language it calculates: size + 64bit
     
    145135                FileChannel fileChannel = new FileInputStream(file).getChannel();
    146136               
    147                 long head = computeHashForChunk(fileChannel, 0, chunkSizeForFile);
    148                 long tail = computeHashForChunk(fileChannel, Math.max(size - HASH_CHUNK_SIZE, 0), chunkSizeForFile);
    149                
    150                 fileChannel.close();
    151                
    152                 return String.format("%016x", size + head + tail);
     137                try {
     138                        long head = computeHashForChunk(fileChannel.map(MapMode.READ_ONLY, 0, chunkSizeForFile));
     139                        long tail = computeHashForChunk(fileChannel.map(MapMode.READ_ONLY, Math.max(size - HASH_CHUNK_SIZE, 0), chunkSizeForFile));
     140                       
     141                        return String.format("%016x", size + head + tail);
     142                } finally {
     143                        fileChannel.close();
     144                }
    153145        }
    154146       
    155147
    156         private static long computeHashForChunk(FileChannel fileChannel, long start, long size) throws IOException {
    157                 MappedByteBuffer byteBuffer = fileChannel.map(MapMode.READ_ONLY, start, size);
    158                
    159                 LongBuffer longBuffer = byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
     148        private static long computeHashForChunk(ByteBuffer buffer) {
     149               
     150                LongBuffer longBuffer = buffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
    160151                long hash = 0;
    161152               
    162153                while (longBuffer.hasRemaining()) {
    163 
    164 
    165 
    166154                        hash += longBuffer.get();
    167155                }