文档库 最新最全的文档下载
当前位置:文档库 › Java如何判断一个文件(夹)被重命名过,除了使用md5码校验?

Java如何判断一个文件(夹)被重命名过,除了使用md5码校验?

Java如何判断一个文件(夹)被重命名过,除了使用md5码校验?

使用File的lastModify方法是不行的,又不想使用md5码来校验,不使用md5来判断是因为md5算法运算大文件时耗时间。况且内容不改变,只改变文件名。

后来使用lastModify+文件的绝对路径来作为依据判断,我做了2个Map来映射,新map和旧map不匹配则会产生新增和删除这2个结果。

这样用来判断文件还是可以的但是文件夹就不行了。如果文件夹下面还有文件(夹),也会被误认为重命名。

有什么其他解决办法吗?或者代码应该如何修改更加好?

代码如下:

public class Main {

public Map map = new HashMap();

public String baseFilePath;

public static void main(String[] args) throws IOException, InterruptedException {

String baseFilePath = "D:\\md5";

Main m = new Main(baseFilePath);

Map oldMap = m.getFileInfo(baseFilePath);

//很长时间过去了

//-------------------各种操作:文件(夹)或修改或删除或新增

----------------

File oldFile = new File(baseFilePath+"\\ddd.txt");//删除

oldFile.delete();

File newFile = new File(baseFilePath+"\\new.txt");//新增

newFile.createNewFile();

File olddir = new File(baseFilePath+"\\test");//重命名

File newdir = new File(baseFilePath+"\\test2");

olddir.renameTo(newdir);

//-------------------操作结束

---------------------------------------

Main m2 = new Main(baseFilePath);

Map newMap = m2.getFileInfo(baseFilePath);

Map resultMap = m.getModifyInfo(oldMap, newMap);

List resultKeys = new ArrayList(resultMap.keySet ());

for(String resultKey:resultKeys){

String resultValue = resultMap.get(resultKey);

System.out.println(resultKey+"---"+resultValue);

}

}

public Main(String baseFilePath){

this.baseFilePath = baseFilePath;

}

/**

* 循环得到目录下的名字和modify时间

* @param baseFile 根目录

* @return Map 相对baseFilePath的路径以及最后修改时间

*/

public Map getFileInfo(String baseFile){

FileOperate fo = new FileOperate();

File[] files = fo.getFileList(baseFile);

for(File file:files){

map.put(file.getAbsolutePath()。substring(baseFilePath.length ()), https://www.wendangku.net/doc/ca513308.html,stModified());//相对baseFilePath的路径以及最后修改时间

if(file.isDirectory()){

getFileInfo(file.getAbsolutePath());//递归

}

}

return map;

}

/**

* 比较目录信息(返回变动的目录信息)

* @param oldMap

* @param newMap

* @return 存放键值对:键是目录值是类型(如文件内容修改,文件(夹)删除,文件(夹)添加)注:文件(夹)重命名属于删除、添加

*/

public Map getModifyInfo(Map oldMap,Map newMap){

Map resultMap = new HashMap();

List oldKeysList = new ArrayList(oldMap.keySet());

List newKeysList = new ArrayList(newMap.keySet());

for(String oldKey:oldKeysList){

long oldValue = oldMap.get(oldKey);

if(newKeysList.contains(oldKey)){//包含此文件(夹)

long newValue = newMap.get(oldKey);

if(oldValue==newValue){//文件(夹)没修改

//continue;

}else{//文件被修改

resultMap.put(oldKey, "修改");

}

}else{//不包含删除

resultMap.put(oldKey, "删除");

}

}

for(String newKey:newKeysList){

if(oldKeysList.contains(newKey)){

//continue;

}else{//新增

resultMap.put(newKey, "新增");

}

}

return resultMap;

}

}

< /STRING,>

PS;本文档由北大青鸟广安门收集自互联网,仅作分享之用。

相关文档