import java.io.*; import java.util.*; public class FindDuplicatedFile { //fileList is the list of files in this directory static private List<File> fileList = new ArrayList<>(); static private void getFileList(String filePath) throws NotDirectoryExpectation{ File file = new File(filePath); if(!file.isDirectory()){ throw new NotDirectoryExpectation(); } File[] fileArray = file.listFiles(); if(fileArray == null) return; for(int i = 0; i<fileArray.length; i++){ if(fileArray[i].isFile()) fileList.add(fileArray[i]); if(fileArray[i].isDirectory()) getFileList(fileArray[i].getAbsolutePath()); } } //to search the directory to find duplicate files public static List<File> getDuplicatedFile(String filePath) throws NotDirectoryExpectation{ getFileList(filePath); List<File > duplicateFiles = new ArrayList<>(); for(int i = 0; i< fileList.size(); i++){ File temp = fileList.get(i); for(int j = i+1; j < fileList.size(); j++){ if(fileList.get(j).getName().equals(temp.getName()) && fileList.get(j).length() == temp.length()) { duplicateFiles.add(fileList.get(j)); duplicateFiles.add(temp); } } } return duplicateFiles; } public static void printDuplicates(List<File> list){ Iterator<File> it = list.iterator(); if(list.size() == 0){ System.out.println("no Duplicated File!"); } while(it.hasNext()){ File temp= it.next(); System.out.println(temp.getName() + ' ' + temp.getAbsolutePath() + ' ' + temp.length()); } } public static void main(String[] args){ String filePath = args[0]; try { printDuplicates(getDuplicatedFile(filePath)); }catch (Exception e){} } static private class NotDirectoryExpectation extends Exception{} }
这个主要就是File类的使用了