1. import java.io.File;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. class FileMetadataAttacher {
  5. /**
  6. * Attaches metadata (file path) to a map. Handles edge cases like null or empty paths.
  7. *
  8. * @param filePaths A variable number of file paths to attach.
  9. * @return A map where keys are arbitrary identifiers and values are the file paths.
  10. * Returns an empty map if filePaths is null or empty.
  11. */
  12. public static Map<String, String> attachFileMetadata(String... filePaths) {
  13. Map<String, String> metadata = new HashMap<>();
  14. if (filePaths == null || filePaths.length == 0) {
  15. return metadata; // Return empty map for null or empty input
  16. }
  17. for (int i = 0; i < filePaths.length; i++) {
  18. String filePath = filePaths[i];
  19. if (filePath == null || filePath.trim().isEmpty()) {
  20. continue; // Skip null or empty paths
  21. }
  22. //Ensure the path is valid
  23. File file = new File(filePath);
  24. if (!file.exists()) {
  25. continue; // Skip if file doesn't exist
  26. }
  27. metadata.put("file_" + i, filePath); // Use a unique identifier
  28. }
  29. return metadata;
  30. }
  31. public static void main(String[] args) {
  32. //Example Usage
  33. Map<String, String> metadata = attachFileMetadata("path/to/file1.txt", "path/to/file2.txt", null, "");
  34. System.out.println(metadata); // Output the metadata map
  35. }
  36. }

Add your comment