For some large files, sometimes you will need to calculate some of the content of the hash, the following function calculates the file tail 1 m, the middle jump 100M take 10K and file size hash value
Public StaticString Calhash (String path)throwsIOException {File file=NewFile (path); if(!File.canread ())return""; if(File.length () < 150 * 1024 * 1024) { return""; } //FileInputStream in = new FileInputStream (file);Randomaccessfile in =NewRandomaccessfile (file, "R"); MessageDigest MessageDigest; Try{messagedigest= Messagedigest.getinstance ("SHA1"); intSzread = 0; intsize_1m = 1024*1024; byte[] buffer =New byte[size_1m]; //file 1 m each tail, middle jump 100M take 10K calculate hash//StartSzread =in.read (buffer); Messagedigest.update (buffer); //EndIn.seek (File.length ()-size_1m); Szread=in.read (buffer); Messagedigest.update (buffer); intBuffer_size = (10 * 1024); Buffer=New byte[(int) Buffer_size]; LongEndpos = File.length ()-1024 * 1024-buffer_size; LongSkipsize = (Long) ( ((float) (File.length ()/(float) (100.0 * 1024.0 * 1024.0)-(float) 1.0) *buffer_size)); LongCurrentpos = 1024 * 1024; In.seek (Currentpos); while(In.getfilepointer () < Endpos && in.read (buffer) > 0) {In.seek (In.getfilepointer ()+skipsize); Messagedigest.update (buffer); } //calculate the hash of the file size LongFsize =file.length (); byte[] Fsizebytes =getBytes (fsize); Messagedigest.update (fsizebytes); returnByte2hex (Messagedigest.digest ()); } Catch(NoSuchAlgorithmException e) {}Catch(OutOfMemoryError e) {}finally{in.close (); } return NULL; }
java-read the file portion of the content to calculate the hash value