1. import java.io.*;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class DatasetSync {
  5. private static final String DEFAULT_FALLBACK_DATASET = "fallback_data.csv";
  6. /**
  7. * Synchronizes resources of datasets, using a fallback dataset if synchronization fails.
  8. *
  9. * @param primaryDatasetPath Path to the primary dataset file.
  10. * @param backupDatasetPath Path to the backup dataset file (fallback).
  11. * @return A Map containing the synchronized dataset data.
  12. * @throws IOException If an I/O error occurs during file reading.
  13. */
  14. public static Map<String, String> syncDatasets(String primaryDatasetPath, String backupDatasetPath) throws IOException {
  15. // Attempt to read from the primary dataset.
  16. Map<String, String> primaryData = readDataset(primaryDatasetPath);
  17. // If successful, return the primary data.
  18. if (primaryData != null) {
  19. return primaryData;
  20. }
  21. // If primary dataset fails, use the fallback dataset.
  22. System.out.println("Primary dataset failed. Using fallback dataset.");
  23. Map<String, String> fallbackData = readDataset(backupDatasetPath);
  24. // If fallback dataset is also empty, return an empty map.
  25. if (fallbackData == null) {
  26. System.out.println("Fallback dataset is also empty. Returning empty map.");
  27. return new HashMap<>();
  28. }
  29. return fallbackData;
  30. }
  31. /**
  32. * Reads a dataset from a CSV file.
  33. *
  34. * @param filePath Path to the CSV file.
  35. * @return A Map representing the dataset, or null if an error occurs.
  36. * @throws IOException If an I/O error occurs.
  37. */
  38. private static Map<String, String> readDataset(String filePath) throws IOException {
  39. Map<String, String> dataset = new HashMap<>();
  40. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  41. String line;
  42. while ((line = reader.readLine()) != null) {
  43. String[] parts = line.split(",");
  44. if (parts.length == 2) {
  45. dataset.put(parts[0].trim(), parts[1].trim());
  46. }
  47. }
  48. } catch (IOException e) {
  49. System.err.println("Error reading dataset: " + e.getMessage());
  50. return null;
  51. }
  52. return dataset;
  53. }
  54. public static void main(String[] args) {
  55. String primaryPath = "primary_data.csv";
  56. String backupPath = DEFAULT_FALLBACK_DATASET;
  57. try {
  58. Map<String, String> synchronizedData = syncDatasets(primaryPath, backupPath);
  59. if (synchronizedData != null) {
  60. System.out.println("Synchronized data: " + synchronizedData);
  61. } else {
  62. System.out.println("Synchronization failed.");
  63. }
  64. } catch (IOException e) {
  65. System.err.println("An error occurred: " + e.getMessage());
  66. }
  67. }
  68. }

Add your comment