java 找出两个文件夹下所有的不同文件

本文介绍了一个用于比较两个项目文件差异的Java工具。该工具能够扫描指定类型的文件(如.jsp),并记录两个文件夹中文件大小不同的文件名,最终将这些信息保存到一个指定的文件中,便于开发者快速定位修改过的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么写这个类咧,因为修改的地方太多了,也不知道修改了哪些文件,(刚跳到一家公司,老大直接拷贝的project给我的,并删掉了SVN相关的文件,防止新员工瞎提交,所以写了这个类,拿Eclipse里的project和老大拷给我的project比较一下,就OK了)。

 

package com.org.ruizi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class FileCompare {
	public FileCompare() {
	}
	private final String type = ".jsp";

	private void getDir(File f,Map<String, Long> map, int level) {
		File[] childs = f.listFiles();
		for (int i = 0; i < childs.length; i++) {
			if (childs[i].isDirectory()) {
				this.getDir(childs[i],map,level + 1);
			}else{
				if(type.equals(childs[i].getName().substring(childs[i].getName().lastIndexOf(".")))){
					map.put(childs[i].getName(), childs[i].length());
				}
			}
		}
	}
	
	/**
	 * 查询两个文件夹下所有的不同文件,并保存到批定的文件中
	 * @param sourceFolder 源文件夹路径
	 * @param targetFolder 目标文件夹路径
	 * @param saveFile     保存的文件路径
	 * @author gzq
	 */
	private void compareFile(String sourceFolder,String targetFolder,String saveFile){
		Map<String, Long> sourceMap = new HashMap<String, Long>();
		Map<String, Long> targetMap = new HashMap<String, Long>();
		new FileCompare().getDir(new File(sourceFolder), sourceMap,0);
		new FileCompare().getDir(new File(targetFolder), targetMap,0);
		
		File f = new File(saveFile);
		if (f.exists()){
			try {
				f.delete();
				f.createNewFile();
			} catch (IOException e) {
				System.out.println(e);
			}
		}
		else{
			try {
				f.createNewFile();
			} catch (IOException e) {
				System.out.println(e);
			}
		}
		String source = null;

		byte[] bytes = null;
		OutputStream os;
		try {
			os = new FileOutputStream(saveFile);

			Set set = sourceMap.entrySet();
			Iterator i = set.iterator();
			while (i.hasNext()) {
				Map.Entry<String, Long> entry1 = (Map.Entry<String, Long>) i.next();
				if (!sourceMap.get(entry1.getKey()).equals(targetMap.get(entry1.getKey()))) {
					source = entry1.getKey()+"\r\n";
					bytes =  source.getBytes();
					
					os.write(bytes);
				}
			}
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args){
		new FileCompare().compareFile("D:\\Users\\Administrator\\Desktop\\A", "D:\\Users\\Administrator\\Desktop\\B", "D:\\Users\\Administrator\\Desktop\\compareFile.txt");
		System.out.println("0");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值