java查找文件重复内容代码怎么写

954
2023/9/24 12:38:41
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

你可以使用Java的File类和BufferedReader类来实现文件内容的查找。以下是一个示例代码,该代码可以查找指定文件夹下所有文件中的重复内容:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class FindDuplicateContent {
public static void main(String[] args) {
// 指定文件夹路径
String folderPath = "your_folder_path";
// 用于存储文件内容和对应的文件路径
Map<String, Set<String>> contentMap = new HashMap<>();
// 遍历文件夹下的所有文件
File folder = new File(folderPath);
for (File file : folder.listFiles()) {
if (file.isFile()) {
String content = getFileContent(file);
if (content != null) {
// 将文件内容作为key,文件路径作为value存入map中
if (contentMap.containsKey(content)) {
contentMap.get(content).add(file.getAbsolutePath());
} else {
Set<String> filePaths = new HashSet<>();
filePaths.add(file.getAbsolutePath());
contentMap.put(content, filePaths);
}
}
}
}
// 输出重复内容和对应的文件路径
for (Set<String> filePaths : contentMap.values()) {
if (filePaths.size() > 1) {
System.out.println("重复内容:" + filePaths);
}
}
}
private static String getFileContent(File file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
return content.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

请将代码中的your_folder_path替换为你要查找的文件夹的路径。运行这段代码后,它会列出重复的文件内容和对应的文件路径。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java二维数组如何定义