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被抹掉了,这里给它加上 } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)