ネイティブに日本語で言い換えると、Javaでファイルの重複した内容を検索するコードはどうやって書きますか
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を、検索対象のフォルダのパスに置き換えてください。このコードを実行すると重複しているファイルの内容とそれに対応するファイルパスが表示されます。