As there is requriement about compare code in two branches , so just write a demo.
function contains:
1.get checksum of string
2.get checksum of files
3.compare two folders.
package com.jsajax.utilities; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; public class ChecksumUtility { public static final String ALGORITHM_MD5="MD5"; public static final String ALGORITHM_SHA1="SHA-1"; public static final String FOLDER_MAIN="SRC"; public static final String FOLDER_COMP="DEST"; /*** * * @param input the string * @param algorithm the algorithm,e.g MD5 or SHA-1 * @return the string for the resulting hash value */ public static String stringChecksum(String input , String algorithm) { try { // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) MessageDigest messageDigest = MessageDigest.getInstance(algorithm); // 输入的字符串转换成字节数组 byte[] inputByteArray = input.getBytes(); // inputByteArray是输入字符串转换得到的字节数组 messageDigest.update(inputByteArray); // 转换并返回结果,也是字节数组,包含16个元素 byte[] resultByteArray = messageDigest.digest(); // 字符数组转换成字符串返回 return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } } /*** * * @param inputFile the file path * @param algorithm the algorithm e.g MD5 or SHA-1 * @return the string for the resulting hash value * @throws IOException */ public static String fileChecksum(String inputFile , String algorithm) throws IOException { // 缓冲区大小 int bufferSize = 256 * 1024; FileInputStream fileInputStream = null; DigestInputStream digestInputStream = null; try { // 拿到一个MD5转换器(同样,这里可以换成SHA1) MessageDigest messageDigest = MessageDigest.getInstance(algorithm); // 使用DigestInputStream fileInputStream = new FileInputStream(inputFile); digestInputStream = new DigestInputStream(fileInputStream, messageDigest); // read的过程中进行MD5处理,直到读完文件 byte[] buffer = new byte[bufferSize]; while (digestInputStream.read(buffer) > 0) ; // 获取最终的MessageDigest messageDigest = digestInputStream.getMessageDigest(); // 拿到结果,也是字节数组,包含16个元素 byte[] resultByteArray = messageDigest.digest(); // 同样,把字节数组转换成字符串 return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } finally { try { digestInputStream.close(); } catch (Exception e) { } try { fileInputStream.close(); } catch (Exception e) { } } } /*** * * @param byteArray array of byte * @return string converted from the byteArray e.g bype[0]=60-->0011 1100-->"3C" */ // 下面这个函数用于将字节数组换成成16进制的字符串 public static String byteArrayToHex(byte[] byteArray) { // 首先初始化一个字符数组,用来存放每个16进制字符 char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F' }; // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制, // 也就是2位十六进制字符(2的8次方等于16的2次方)) char[] resultCharArray = new char[byteArray.length * 2]; // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } // 字符数组组合成字符串返回 return new String(resultCharArray); } /*** * * @param srcFolder E:\document\java\test\main\XXX * @param destFolder E:\document\java\test\comp\XXX * @remark when compare the 2 folders , the structure under XXX should be same. * @param firstSameFolderName XXX * @param outputFolder the output folder about the compare result. * @return the checksum of both folders. */ public static void folderCompare(String srcFolder,String destFolder,String firstSameFolderName,String outputFolder){ File srcF = new File(srcFolder); File destF = new File(destFolder); Map<String,String> srcChecksumMap= new HashMap<String,String>(); Map<String,String> destChecksumMap= new HashMap<String,String>(); List<String> allFileList = new ArrayList<String>(); List<String> deleteList = new ArrayList<String>(); List<String> copyList = new ArrayList<String>(); if(srcF.exists()&&srcF.canRead() && destF.exists() && destF.canRead()){ getFileChecksum(srcF,srcChecksumMap,firstSameFolderName); getFileChecksum(destF,destChecksumMap,firstSameFolderName); gatherAllFiles(srcChecksumMap,destChecksumMap,allFileList); System.out.println("srcFolder = "+srcFolder); System.out.println("destFolder = "+destFolder); if(allFileList.size()>0){ int index = 1; String srcFileSum; String descFileSum; for(String str : allFileList){ srcFileSum = srcChecksumMap.get(str); descFileSum = destChecksumMap.get(str); if(StringUtils.isBlank(srcFileSum) && StringUtils.isNotBlank(descFileSum)){ System.out.println("File["+index+"] = "+str+"\t\tTO_DELETE"); deleteList.add(destFolder+"\\"+str); }else if(StringUtils.isNotBlank(srcFileSum) && StringUtils.isBlank(descFileSum)){ System.out.println("File["+index+"] = "+str+"\t\tTO_COPY"); copyList.add(str); }else if(StringUtils.isNotBlank(srcFileSum) && StringUtils.isNotBlank(descFileSum) && !srcFileSum.equalsIgnoreCase(descFileSum)){ System.out.println("File["+index+"] = "+str+"\t\tTO_MODIFY"); copyList.add(str); }else{ System.out.println("File["+index+"] = "+str); } System.out.println("Checksum in srcFolder = "+srcFileSum +"\t\t in destFolder = "+descFileSum); index++; } } }else{ System.out.println("Both folder can not be read."); } System.out.println("Delete below files:"); deleteBelowFiles(deleteList); System.out.println("Copy out below files:"); copyBelowFIles(copyList,srcFolder,outputFolder); } public static void copyBelowFIles(List<String> copyList,String from , String to){ if(copyList.size()>0){ File f; try { for(String s:copyList){ f = new File(to+File.separator+s); CopyUtility.copyFile(from+File.separator+s, to+File.separator+s); } } catch (Exception e) { e.printStackTrace(); } } } public static void deleteBelowFiles(List<String> deleteList){ if(deleteList.size()>0){ for(String s:deleteList){ System.out.println(s); //TODO... } } } public static void gatherAllFiles(Map<String,String> srcChecksumMap,Map<String,String> destChecksumMap , List<String> allFileList){ Set<String> srcFileList = srcChecksumMap.keySet(); Set<String> destFileList = destChecksumMap.keySet(); if(srcFileList.size()>0){ for(String s:srcFileList){ if(!allFileList.contains(s)){ allFileList.add(s); } } } if(destFileList.size()>0){ for(String s:destFileList){ if(!allFileList.contains(s)){ allFileList.add(s); } } } } /*** * * @param file the File entity of file path "E:\document\java\test\main\XXX" * @param checksumMap the result checksum map * @param firstSameFolderName it is XXX */ public static void getFileChecksum(File file,Map<String,String> checksumMap,String firstSameFolderName){ if(file.isFile()){ String relativePath = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(firstSameFolderName)+firstSameFolderName.length()+1); try { checksumMap.put(relativePath, fileChecksum(file.getAbsolutePath() , ChecksumUtility.ALGORITHM_SHA1)); } catch (IOException e) { checksumMap.put(relativePath,"encounter exception."); } return; }else{ File[] files = file.listFiles(); if(files !=null && files.length >0){ for(File f : files){ if(!f.getName().startsWith(".")){ // if the directory or file name is started with '.' , ignore it getFileChecksum(f,checksumMap,firstSameFolderName); } } }else{ return; } } } public static void main(String[] args) { ChecksumUtility.folderCompare("E:\\document\\java\\111111testfolder\\main\\123", "E:\\document\\java\\111111testfolder\\comp\\123", "123", "E:\\document\\java\\111111testfolder\\result"); } }
package com.jsajax.utilities; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class CopyUtility { public static void createDir(String fileToPath){ String folder = fileToPath.substring(0,fileToPath.lastIndexOf(File.separator)); File f = new File(folder); if(!f.exists()){ System.out.println("Create folder "+folder); f.mkdirs(); } } public static void createFile(String fileToPath) throws IOException{ File f = new File(fileToPath); if(!f.exists()){ System.out.println("Create file "+fileToPath); f.createNewFile(); } } public static void copyFile(String fileFromPath, String fileToPath){ InputStream in = null; OutputStream out = null; try { createDir(fileToPath); createFile(fileToPath); in = new FileInputStream(fileFromPath); out = new FileOutputStream(fileToPath); int length = in.available(); int len = (length % 1024 == 0) ? (length / 1024): (length / 1024 + 1); byte[] temp = new byte[1024]; for (int i = 0; i < len; i++) { in.read(temp); out.write(temp); } } catch(Exception e){ e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
相关推荐
例如,在Java中使用`File`类来处理文件路径。 **Class [klɑ:s]**:类。类是面向对象编程中的一个核心概念,它定义了对象的属性和行为。例如,可以定义一个名为`Person`的类来表示一个人。 **Classpath [klɑ:s'p...
4.3.5. Zend_Cache_Frontend_File 4.3.5.1. Introduction 4.3.5.2. Available options 4.3.5.3. Examples 4.3.6. Zend_Cache_Frontend_Page 4.3.6.1. Introduction 4.3.6.2. Available options (for this ...
Packages ...com.kingdee.bos.metadata.compare ...com.kingdee.bos.util.backport.concurrent.helpers Auxiliary and helper classes for backport.util.concurrent, NOT present in java.util.concurrent. ...
本科生计算机组成原理题库期末试卷及答案.doc
计算机系统结构电子教案.pptx
计算机的操作规程.doc
【目标检测】道路坑洞数据集2944张YOLO+VOC(已增强).docx
计算机考研专业课知识点分析.doc
计算机专业毕业设计题目大全.doc
湖北师范学院专升本C语言程序设计试卷.doc
计算机应用基础国家开放大学模块五.doc
ssm043基于JavaEE的龙腾公司员工信息管理系统的设计与实现(文档+源码)_kaic
【目标检测】苹果叶片病害数据集4类标签8223张YOLO+VOC格式.docx
网络中心机房建设解决方案模板.doc
数据集介绍:动物与应急车辆目标检测数据集 一、基础信息 数据集名称:动物与应急车辆目标检测数据集 数据规模: - 训练集:8,292张图片 - 验证集:346张图片 - 测试集:345张图片 - 总计:8,983张标注图片 分类类别: - 救护车(Ambulance):应急医疗车辆识别 - 动物(Animal):通用动物类别检测 - 蚂蚁(Ant):小型昆虫识别 - 羚羊(Antelope):草原动物检测 标注格式: YOLO格式标注,支持目标检测任务,含归一化坐标和类别编码 二、适用场景 野生动物监测系统: 支持自然保护区构建动物分布监测系统,识别羚羊等特定物种活动轨迹 应急车辆识别系统: 适用于智能交通管理系统开发,实现救护车等应急车辆的快速识别 生物多样性研究: 提供蚂蚁等昆虫类别的检测数据,支持生态学研究中的物种分布分析 农业监控应用: 适用于害虫监测场景,帮助识别田间蚂蚁等昆虫的分布密度 三、数据集优势 多场景覆盖: 同时包含野生动物(羚羊)、常见动物(通用动物)和特殊车辆(救护车)检测目标 精细分类体系: 区分通用动物与特定物种(蚂蚁/羚羊),支持不同粒度的检测需求 工业级数据规模: 超8,000张训练样本,满足深度学习模型的训练需求 任务适配性强: 原生YOLO格式标注可直接应用于主流目标检测框架(YOLOv5/v8等) 跨领域应用: 同时支持自然环境保护、城市交通管理和农业监测等多领域应用场景
电子商务代运营服务合作协议书.doc
福建省第三届大学生程序设计竞赛题目.doc
计算机软件与理论专业研究生培养方案.doc
讲座网络平台下小学生有效学习方式的研究.doc