请使用java写一个利用MD5码查找目录下的相同重复文件
时间: 2024-06-04 14:11:04 浏览: 10
以下是一个基本的Java程序,用于查找目录中的重复文件:
import java.io.*;
import java.security.*;
import java.util.*;
public class FindDuplicateFiles {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FindDuplicateFiles <directory>");
System.exit(1);
}
String directory = args[0];
// Create a map to store the file hashes and their corresponding file paths
Map<String, List<String>> fileMap = new HashMap<>();
// Traverse the directory and compute the MD5 hash for each file
try {
File dir = new File(directory);
if (!dir.isDirectory()) {
System.out.println(directory + " is not a directory");
System.exit(1);
}
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
continue;
}
String hash = computeHash(file);
if (fileMap.containsKey(hash)) {
fileMap.get(hash).add(file.getAbsolutePath());
} else {
List<String> fileList = new ArrayList<>();
fileList.add(file.getAbsolutePath());
fileMap.put(hash, fileList);
}
}
// Print out the duplicate files
for (List<String> fileList : fileMap.values()) {
if (fileList.size() > 1) {
System.out.println("Duplicate Files:");
for (String filePath : fileList) {
System.out.println(filePath);
}
System.out.println();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String computeHash(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = new FileInputStream(file)) {
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) > 0) {
md.update(buffer, 0, read);
}
byte[] hash = md.digest();
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
}
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)