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

avatar
作者
猴君
阅读量:1

你可以使用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替换为你要查找的文件夹的路径。运行这段代码后,它会列出重复的文件内容和对应的文件路径。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!