Android编写一个搜索指定路径下所有重复文件的函数
时间: 2024-05-10 20:19:53 浏览: 15
可以使用哈希表(Hash Table)来实现。遍历指定路径下的所有文件,对每个文件进行哈希处理,如果该哈希值已经存在于哈希表中,则说明找到了重复文件,将其路径存储到一个列表中。最后返回该列表即可。以下是部分示例代码(仅供参考):
```java
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
public class FileSearch {
public static void main(String[] args) {
String path = "指定路径";
ArrayList<String> duplicates = searchDuplicates(path);
System.out.println(duplicates.toString());
}
public static ArrayList<String> searchDuplicates(String path) {
File dir = new File(path);
if (!dir.isDirectory()) {
throw new IllegalArgumentException("Path is not a directory.");
}
HashMap<String, String> hashTable = new HashMap<>();
ArrayList<String> duplicates = new ArrayList<>();
try {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
duplicates.addAll(searchDuplicates(file.getPath()));
} else {
String md5 = getMD5(file);
String existing = hashTable.get(md5);
if (existing != null) {
duplicates.add(existing);
duplicates.add(file.getPath());
} else {
hashTable.put(md5, file.getPath());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return duplicates;
}
private static String getMD5(File file) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
fis.close();
BigInteger bigInt = new BigInteger(1, md.digest());
return bigInt.toString(16);
}
}
```
请注意,该方法只能找到哈希值相同的文件,并不一定是完全相同的文件。如果存在两个或多个不同的文件,它们的哈希值相同,该方法将视为重复文件。为了降低误判率,可以在哈希表中存储文件大小信息,并在比较哈希值前先比较文件大小。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.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)