java对比文件夹下的png图片

java对比文件夹下的png图片

java获取电脑文件夹下面所有的png格式文件,然后对比相同文件,如有没有两张或以上是一样的,然后把文件名和路径导出来,并生成excle文件
需要使用到poi,可通过下面网址下载

https://download.csdn.net/download/xuguoxing123/11390874

文件保存器

public class FileSavers {
	private File compareFile;
	private List<File> sameFile;
	/*
	 * public FileSavers(File compareFile,File sameFile) { this.compareFile =
	 * compareFile; this.sameFile = sameFile; }
	 */
	public File getCompareFile() {
		return compareFile;
	}
	public void setCompareFile(File compareFile) {
		this.compareFile = compareFile;
	}
	public List<File> getSameFile() {
		return sameFile;
	}
	public void setSameFile(List<File> sameFile) {
		this.sameFile = sameFile;
	}
}

将文件路径导入excle中

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelManage {
    public static void excelExport(List<FileSavers> theSameFileData) {
    	//创建HSSFWorkbook对象(excel的文档对象)  
    	HSSFWorkbook wb = new HSSFWorkbook();  
    	//建立新的sheet对象(excel的表单),即工作区间  
    	HSSFSheet sheet=wb.createSheet("export");
    	//设置列宽(第一个参数代表列序号,第二个参数代表宽度)
    	sheet.setColumnWidth(0,100*148); 
    	sheet.setColumnWidth(1,100*148);
    	//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个  
    	HSSFRow rowTitle=sheet.createRow(0);
    	//设置行高
    	rowTitle.setHeight((short)600); 
    	//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个  
    	HSSFCell cell=rowTitle.createCell(0); 
    	//定义标题的样式
    	HSSFCellStyle cellTileStyle = wb.createCellStyle();
    	//水平对齐
    	cellTileStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
    	//垂直对齐
    	cellTileStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    	//自动换行
    	cellTileStyle.setWrapText(true);
    	//创建标题的字体样式
    	HSSFFont  fontTitleStyle = wb.createFont();
    	//设置字体高度  
    	fontTitleStyle.setFontHeightInPoints((short)14); 
    	//加粗
    	fontTitleStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    	//通过上面定义的cellTileStyle,设置当前样式的字体样式属性
    	cellTileStyle.setFont(fontTitleStyle);
    	//设置单元格内容  
    	cell.setCellValue("重复资源路径导出内容");  
    	//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列  
    	sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
    	//添加样式要单元格中
    	cell.setCellStyle(cellTileStyle);
    	//创建第二行,用于填写列名
    	HSSFRow row2=sheet.createRow(1);
    	//当前行第一列的值
    	row2.createCell(0).setCellValue("比较文件路径");
    	//当前行第二列的值
    	row2.createCell(1).setCellValue("重复文件路径");
    	//从第三行开始遍历数据,以rowIndex为索引
    	int rowIndex = 2;
    	for(FileSavers fileSavers : theSameFileData) {
    		//每遍历一次,创建一个行对象,可以理解为新增一个空行,此时该行还没有列数据(即单元格的数据)
    		HSSFRow rowContent = sheet.createRow(rowIndex++);
    		//如果相同的列表不为空,则不用显示在表格中
    		if(fileSavers != null && fileSavers.getSameFile().size() != 0) {
    			//第一列
        		int cellcount = 0;
        		rowContent.createCell(0).setCellValue(fileSavers.getCompareFile().toString());
        		for(File sameFile:fileSavers.getSameFile()) {
        			rowContent.createCell(cellcount++).setCellValue(sameFile.toString());
        		}
    		}
    	}	
    	//输出Excel文件  
		try {
			FileOutputStream output = new FileOutputStream("d:\\workbook1.xls");
			wb.write(output);
	    	output.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
    }
}

通过for循环遍历文件,将文件夹下路径打印出来并对相同文件进行比较

public class Test {
	public static List<File[]> fileList = new ArrayList<File[]>();
	//通过list集合来收集FileSavers对象,以便能在文件操作流中简单遍历
	public static List<FileSavers> theSameFileData = new ArrayList<FileSavers>();
	
    public static String md5(byte[] s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s;
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            // 移位 输出字符串
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static byte[] getByte(File name) {
        // 得到文件长度
        byte[] b = new byte[(int) name.length()];
        return b;
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("重复文件寻找");
        System.out.print("请输入要检查的文件夹:");
        BufferedReader input = new BufferedReader(new InputStreamReader(
                System.in));
        File dir = new File(input.readLine());//读取输入的文件路径
//        File dir =new File("E:\\work\\FGUI\\FGUI");
        if (!dir.exists()) {
            System.out.println("找不到指定目录");
            return;
        }
        System.out.print("确认开始检查(Y/N?):");
        String KorT = sc.next();
        if (!KorT.equals("Y") && !KorT.equals("y")) {
            System.out.println("程序结束!");
            return;
        }
        System.out.println("当前进度:0%");
        pick(dir);//获取所有文件夹下的照片路径名称
        searchSameFile();//获取比较文件和相同文件的List集合
        ExcelManage.excelExport(theSameFileData);//导出文件
        System.out.println("当前进度:100%");
        System.out.println("检查完成!");
    }
    public static void pick(File dir){

        File[] files = dir.listFiles(new FileFilter() {
            // 判断是否是以png结尾的文件
            @Override
            public boolean accept(File file) {
                if (file.getName().toLowerCase().endsWith(".png")) {
                    return true;
                }
                if (file.isDirectory()) {
                    pick(file);
                }
                return false;
            }
        });
        fileList.add(files);
    }
    
    public static void searchSameFile(){
    	for(int index1 = 0 ; index1<fileList.size();index1++) {
          	 for (int i = 0; i < fileList.get(index1).length; i++) { //将png图片文件进行对比
                   if(fileList.get(index1)[i]==null)
                       continue;
                   //新建一个文件保存器对象
                   FileSavers fileSavers = new FileSavers();
                   //首先存储比较文件的内容
                   fileSavers.setCompareFile(fileList.get(index1)[i]);
                   //新建一个相同文件列表参数,用于接收相同文件的数据,并且赋值给文件保存器对象
                   List<File> sameFileList = new ArrayList<File>();
                   //遍历文件列表进行对比
                   for(int index2=index1+1;index2 < fileList.size();index2++){
                  	 for(int j = 0 ; j < fileList.get(index2).length;j++) {
                  		 if(fileList.get(index2)==null)
                               continue;
                           if(fileList.get(index2)[j].length()==fileList.get(index1)[i].length()){
                               String img1 = md5(getByte(fileList.get(index1)[i]));
                               String img2 = md5(getByte(fileList.get(index2)[j]));
                               if(img1.equals(img2)){
                                   try{
                                	   sameFileList.add(fileList.get(index2)[j]);
                                   }catch(Exception ee){
                                       System.out.println("检查失败:"+fileList.get(index2)[j]);
                                   }
                               }
                           }
                           else
                               continue;
                       }
                  	}
                   fileSavers.setSameFile(sameFileList);
                   theSameFileData.add(fileSavers);
               }
          }
    }

可能导出的excle文件有点不好看,可以自己进行微调
如有不足之处请大佬们提点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值