当前位置:   article > 正文

java 批量计算某个文件夹下所有文件的md5_批量计算md5值

批量计算md5值

1.需要的jar包
poi-3.14-20160307.jar
poi-ooxml-3.14-20160307.jar
poi-ooxml-schemas-3.14-20160307.jar
xmlbeans-2.6.0.jar
2. 完整代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//批量计算文件夹下的md5
public class calc_md5 {
	static XSSFWorkbook workbook = new XSSFWorkbook();
	static XSSFSheet sheet = workbook.createSheet("测试");
	static XSSFRow row = sheet.createRow(0); //表头
	static int i = 1;
	
	public static void main(String[] args) throws IOException {
		File f = new File("xxx");//要计算md5的文件夹路径	
		String filename = f.getName();
		//设置表头名称
		row.createCell(0).setCellValue("文件名");
		row.createCell(1).setCellValue("md5");
		findFile(f);		
		FileOutputStream fileOut = new FileOutputStream("xxx.xlsx");
		workbook.write(fileOut);//将计算结果保存到xxx.xlsx
		fileOut.flush();
		fileOut.close();
		workbook.close();
	}
	
	//遍历文件夹,写入excel
	public static void findFile(File f) throws IOException {//计算md5并写入excel
				
		File[] flist = f.listFiles();
		for (File file : flist) { 
			if(file.isDirectory()) {
				findFile(file); //递归遍历文件夹下的所有文件
			}else {
				String md5 = getMd5(file.getAbsolutePath());
				XSSFRow newrow = sheet.createRow(i);
				newrow.createCell(0).setCellValue(file.getName());
				newrow.createCell(1).setCellValue(md5);
				i++;
			}			
		}		
	}
	//计算单个文件的md5
	public  static String getMd5(String path) {
		BigInteger bi = null;
		try {
			byte[] buffer = new byte[8192];
			int len = 0;
			MessageDigest md = MessageDigest.getInstance("MD5");
			File f = new File(path);
			FileInputStream fis = new FileInputStream(f);
			while((len=fis.read(buffer))!=-1) {
				md.update(buffer, 0, len);
			}
			fis.close();
			byte[] b = md.digest();
			bi = new BigInteger(1,b);		
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return bi.toString(16).length()==32?bi.toString(16):"0"+bi.toString(16);
		//BigInteger会排除第一个0,所以如果不等于32就是第一个0被抹掉了,这里给它加上
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/517019
推荐阅读
相关标签
  

闽ICP备14008679号