比较两个文件夹下不同的文件-第二版

本版增加了,文件后前后缀, 文件夹递归:

package com.log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CompareFile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String fold1Path="/Users/xx/eclipse-workspace/springboot-data/out";
		Set<String> fold1=new HashSet<String>(getAll(new File(fold1Path),fold1Path,".docx"));
		
		
		String fold2Path="/Users/xx/Desktop/pdf";
		Set<String> fold2=new HashSet<String>(getAll(new File(fold2Path),fold2Path,".pdf"));
		
		
		Set<String> same=new HashSet<String>();
		for(String f:fold1) {
			if(fold2.contains(f)) {
				same.add(f);
			}
		}
		for(String f:fold2) {
			if(fold1.contains(f)) {
				same.add(f);
			}
		}
		
		
		for(String s:same) {
			fold1.remove(s);
			fold2.remove(s);
		}
		System.out.println(fold1Path+"多余文件:");
		System.out.println(fold1);
		System.out.println(fold2Path+"多余文件:");
		System.out.println(fold2);
		
		
	}
	
	public static List<String> getAll(File f,String prefix,String suffix){
		List<String> cs=loopAll(f);
		List<String> ncs=new ArrayList<>();
		for(String s:cs) {
			ncs.add(s.replace(prefix, "").replace(suffix, ""));
		}
		return ncs;
	}
	public static List<String> loopAll(File f){
		List<String> cs=new ArrayList<>();
		File[] children=f.listFiles();
		if(children!=null) {
			for(File c:children) {
				if(c.isDirectory()) {
					cs.addAll(loopAll(c));
				}else {
					cs.add(c.getAbsolutePath());
				}
			}
		}
		return cs;
	}

}

文/中中 浏览次数:0次   2020-03-24 19:52:34

相关阅读


评论: