import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
class MetadataIndexer {
// Represents a metadata entry
static class MetadataEntry {
String filePath;
Map<String, String> metadata;
MetadataEntry(String filePath, Map<String, String> metadata) {
this.filePath = filePath;
this.metadata = metadata;
}
}
// Main method to index metadata
public static List<MetadataEntry> indexMetadata(String rootDir) throws IOException {
List<MetadataEntry> entries = new ArrayList<>();
Path root = Paths.get(rootDir);
if (!Files.exists(root) || !Files.isDirectory(root)) {
System.err.println("Invalid root directory: " + rootDir);
return entries; // Return empty list for invalid input
}
File rootFile = root.toFile();
File[] files = rootFile.listFiles();
if (files == null) {
System.err.println("Could not list files in: " + rootDir);
return entries;
}
for (File file : files) {
if (file.isFile()) {
try {
// Extract metadata from file (example: file name, modification date)
Map<String, String> metadata = extractMetadata(file);
entries.add(new MetadataEntry(file.getAbsolutePath(), metadata));
} catch (IOException e) {
System.err.println("Error processing file: " + file.getAbsolutePath() + ", " + e.getMessage());
}
} else if (file.isDirectory()) {
// Recursively index subdirectories
indexMetadata(file.getAbsolutePath());
}
}
return entries;
}
// Extract metadata from a file (example implementation)
private static Map<String, String> extractMetadata(File file) throws IOException {
Map<String, String> metadata = new HashMap<>();
metadata.put("file_name", file.getName()); // File name
metadata.put("file_path", file.getAbsolutePath()); //File path
metadata.put("last_modified", file.lastModified() + ""); // Last modified timestamp
return metadata;
}
public static void main(String[] args) throws IOException {
// Example usage:
String rootDirectory = "."; // Current directory. Change this to your desired root.
List<MetadataEntry> indexedData = indexMetadata(rootDirectory);
// Print the indexed metadata
for (MetadataEntry entry : indexedData) {
System.out.println("File: " + entry.filePath);
System.out.println("Metadata: " + entry.metadata);
System.out.println("---");
}
}
}
Add your comment