Java gets the MD5 value of the file

Source: Internet
Author: User

Package com.sichang.util;


Import Java.io.File;

Import Java.io.FileInputStream;

Import Java.math.BigInteger;

Import Java.security.MessageDigest;

Import Java.util.HashMap;

Import Java.util.Map;


public class Filedigest {

/**

* Get the MD5 value of a single file!

* @param file

* @return

*/

public static String getFileMD5 (file file) {

if (!file.isfile ()) {

return null;

}

MessageDigest digest = null;

FileInputStream In=null;

byte buffer[] = new byte[1024];

int Len;

try {

Digest = messagedigest.getinstance ("MD5");

in = new FileInputStream (file);

while (len = in.read (buffer, 0, 1024))! =-1) {

Digest.update (buffer, 0, Len);

}

In.close ();

} catch (Exception e) {

E.printstacktrace ();

return null;

}

BigInteger bigInt = new BigInteger (1, Digest.digest ());

return bigint.tostring (16);

}

/**

* Gets the MD5 value of the file in the folder

* @param file

* @param listchild; True recursively files in subdirectories

* @return

*/

public static map<string, string> getDirMD5 (File File,boolean listchild) {

if (!file.isdirectory ()) {

return null;

}

<filepath,md5>

Map<string, string> map=new hashmap<string, string> ();

String MD5;

File Files[]=file.listfiles ();

for (int i=0;i<files.length;i++) {

File F=files[i];

if (F.isdirectory () &&listchild) {

Map.putall (GetDirMD5 (f, listchild));

} else {

MD5=GETFILEMD5 (f);

if (md5!=null) {

Map.put (F.getpath (), MD5);

}

}

}

return map;

}


}


Java gets the MD5 value of the file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.