1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. public class TextFileIndexer {
  10. public static Map<String, List<String>> indexTextFiles(String directoryPath) {
  11. Map<String, List<String>> index = new HashMap<>();
  12. File directory = new File(directoryPath);
  13. if (!directory.exists() || !directory.isDirectory()) {
  14. System.err.println("Invalid directory path: " + directoryPath); //Error handling
  15. return index;
  16. }
  17. File[] files = directory.listFiles();
  18. if (files != null) {
  19. for (File file : files) {
  20. if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) {
  21. try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  22. String line;
  23. while ((line = reader.readLine()) != null) {
  24. // Tokenize the line (simple example: split by spaces)
  25. String[] tokens = line.toLowerCase().split("\\s+");
  26. for (String token : tokens) {
  27. if (!token.isEmpty()) { // Avoid empty tokens
  28. index.computeIfAbsent(token, k -> new ArrayList<>()).add(file.getName());
  29. }
  30. }
  31. }
  32. } catch (IOException e) {
  33. System.err.println("Error reading file: " + file.getName() + " - " + e.getMessage()); //Error handling
  34. }
  35. }
  36. }
  37. }
  38. return index;
  39. }
  40. public static void main(String[] args) {
  41. // Example usage:
  42. String directoryPath = "test_files"; // Replace with your directory
  43. Map<String, List<String>> index = indexTextFiles(directoryPath);
  44. // Print the index (optional)
  45. for (Map.Entry<String, List<String>> entry : index.entrySet()) {
  46. System.out.println(entry.getKey() + ": " + entry.getValue());
  47. }
  48. }
  49. }

Add your comment