1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6. import java.util.*;
  7. class MetadataIndexer {
  8. // Represents a metadata entry
  9. static class MetadataEntry {
  10. String filePath;
  11. Map<String, String> metadata;
  12. MetadataEntry(String filePath, Map<String, String> metadata) {
  13. this.filePath = filePath;
  14. this.metadata = metadata;
  15. }
  16. }
  17. // Main method to index metadata
  18. public static List<MetadataEntry> indexMetadata(String rootDir) throws IOException {
  19. List<MetadataEntry> entries = new ArrayList<>();
  20. Path root = Paths.get(rootDir);
  21. if (!Files.exists(root) || !Files.isDirectory(root)) {
  22. System.err.println("Invalid root directory: " + rootDir);
  23. return entries; // Return empty list for invalid input
  24. }
  25. File rootFile = root.toFile();
  26. File[] files = rootFile.listFiles();
  27. if (files == null) {
  28. System.err.println("Could not list files in: " + rootDir);
  29. return entries;
  30. }
  31. for (File file : files) {
  32. if (file.isFile()) {
  33. try {
  34. // Extract metadata from file (example: file name, modification date)
  35. Map<String, String> metadata = extractMetadata(file);
  36. entries.add(new MetadataEntry(file.getAbsolutePath(), metadata));
  37. } catch (IOException e) {
  38. System.err.println("Error processing file: " + file.getAbsolutePath() + ", " + e.getMessage());
  39. }
  40. } else if (file.isDirectory()) {
  41. // Recursively index subdirectories
  42. indexMetadata(file.getAbsolutePath());
  43. }
  44. }
  45. return entries;
  46. }
  47. // Extract metadata from a file (example implementation)
  48. private static Map<String, String> extractMetadata(File file) throws IOException {
  49. Map<String, String> metadata = new HashMap<>();
  50. metadata.put("file_name", file.getName()); // File name
  51. metadata.put("file_path", file.getAbsolutePath()); //File path
  52. metadata.put("last_modified", file.lastModified() + ""); // Last modified timestamp
  53. return metadata;
  54. }
  55. public static void main(String[] args) throws IOException {
  56. // Example usage:
  57. String rootDirectory = "."; // Current directory. Change this to your desired root.
  58. List<MetadataEntry> indexedData = indexMetadata(rootDirectory);
  59. // Print the indexed metadata
  60. for (MetadataEntry entry : indexedData) {
  61. System.out.println("File: " + entry.filePath);
  62. System.out.println("Metadata: " + entry.metadata);
  63. System.out.println("---");
  64. }
  65. }
  66. }

Add your comment