import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TextFileIndexer {
public static Map<String, List<String>> indexTextFiles(String directoryPath) {
Map<String, List<String>> index = new HashMap<>();
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
System.err.println("Invalid directory path: " + directoryPath); //Error handling
return index;
}
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
// Tokenize the line (simple example: split by spaces)
String[] tokens = line.toLowerCase().split("\\s+");
for (String token : tokens) {
if (!token.isEmpty()) { // Avoid empty tokens
index.computeIfAbsent(token, k -> new ArrayList<>()).add(file.getName());
}
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + file.getName() + " - " + e.getMessage()); //Error handling
}
}
}
}
return index;
}
public static void main(String[] args) {
// Example usage:
String directoryPath = "test_files"; // Replace with your directory
Map<String, List<String>> index = indexTextFiles(directoryPath);
// Print the index (optional)
for (Map.Entry<String, List<String>> entry : index.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Add your comment