java获取文件md5码

本文介绍如何使用Java编写小工具,以校验从非官方渠道下载的文件的MD5码,确保文件的完整性和安全性。提供了一个百度网盘链接供参考。
摘要由CSDN通过智能技术生成

最近下载了一些文件,不是官方的,为了核对MD5码写了一个java版本的,小工具。

package pri.yang.MD5;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

public class BigFileMD5 {
	static MessageDigest MD5 = null;
	
	static{
		try{
			MD5 = MessageDigest.getInstance("MD5");
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		if(args.length < 1){
			System.out.println("need one argument as file path!");
		}else{
			String filePath = args[0];
			//File file = new File("F:\\BaiduYunDownload\\jdk-7u79-linux-x64.tar.gz");
			File file = new File(filePath);
			if(!file.exists()){
				System.out.println("incorrect file path!");
			}else{
				String md5 = getMD5(file);
				System.out.println("===============MD5===============");
				System.out.println(md5);
				System.out.println("===============MD5===============");
				
			}
			
		}
	}
	
	/**
     * 对一个文件获取md5值
     * @return md5串
     */
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
        fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
            	MD5.update(buffer, 0, length);
            }

            return new String(Hex.encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
        e.printStackTrace();
            return null;
        } catch (IOException e) {
        e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


百度网盘:http://pan.baidu.com/s/1bgUFHc



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值