比较2个目录中,哪些文件是重复的,哪些文件是不重复的!

来源:互联网 发布:seo外链群发工具 编辑:程序博客网 时间:2024/05/20 02:28
 

package p;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 比较2个目录中,哪些文件是重复的,哪些文件是不重复的。
 *
 *
 *
 */
public class Demo {

 public List fileList = new ArrayList();

 public static void main(String[] args) {

  String dir1 = "C:\\ear\\tom\\WEB-INF\\classes\\com";
  String dir2 = "C:\\ear\\tom\\WEB-INF\\_srv\\work";
  List arrayList1 = new Demo().getListFiles(dir1, "class", true);
  List arrayList2 = new Demo().getListFiles(dir2, "class", true);
  int ii = 0;

  for (Iterator iter2 = arrayList2.iterator(); iter2.hasNext();) {
   boolean b = false;
   String element2 = (String) iter2.next();
   String s2 = element2.substring(element2.indexOf("com\\"));
   for (Iterator iter1 = arrayList1.iterator(); iter1.hasNext();) {
    String element1 = (String) iter1.next();
    String s1 = element1.substring(element1.indexOf("com\\"));
    if (s2.compareTo(s1) == 0) {
     System.err.println("重复的文件有:"+s2+"\n"+s1+"\n"+(ii+1)+"===="+element1+"\n-----------------------------------");
     b = true;
     break;
    }
   }
   if (!b) {
    System.err.println("目录2中有,但在目录1中没有的class文件有:" + element2);
   }
   ii++;
  }
 }

 /**
  *
  * @param path
  *            文件路径
  * @param suffix
  *            后缀名
  * @param isdepth
  *            是否遍历子目录
  * @return
  */
 public List getListFiles(String path, String suffix, boolean isdepth) {
  File file = new File(path);
  return listFile(file, suffix, isdepth);
 }

 public List listFile(File f, String suffix, boolean isdepth) {
  // 是目录,同时需要遍历子目录
  if (f.isDirectory() && isdepth == true) {
   File[] t = f.listFiles();
   for (int i = 0; i < t.length; i++) {
    listFile(t[i], suffix, isdepth);
   }
  } else {
   String filePath = f.getAbsolutePath();

   if (suffix != null) {
    int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
    String tempsuffix = "";

    if (begIndex != -1)// 防止是文件但却没有后缀名结束的文件
    {
     tempsuffix = filePath.substring(begIndex + 1, filePath
       .length());
    }

    if (tempsuffix.equals(suffix)) {
     fileList.add(filePath);
    }
   } else {
    // 后缀名为null则为所有文件
    fileList.add(filePath);
   }

  }

  return fileList;
 }
}