import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class DatasetSync {
private static final String DEFAULT_FALLBACK_DATASET = "fallback_data.csv";
/**
* Synchronizes resources of datasets, using a fallback dataset if synchronization fails.
*
* @param primaryDatasetPath Path to the primary dataset file.
* @param backupDatasetPath Path to the backup dataset file (fallback).
* @return A Map containing the synchronized dataset data.
* @throws IOException If an I/O error occurs during file reading.
*/
public static Map<String, String> syncDatasets(String primaryDatasetPath, String backupDatasetPath) throws IOException {
// Attempt to read from the primary dataset.
Map<String, String> primaryData = readDataset(primaryDatasetPath);
// If successful, return the primary data.
if (primaryData != null) {
return primaryData;
}
// If primary dataset fails, use the fallback dataset.
System.out.println("Primary dataset failed. Using fallback dataset.");
Map<String, String> fallbackData = readDataset(backupDatasetPath);
// If fallback dataset is also empty, return an empty map.
if (fallbackData == null) {
System.out.println("Fallback dataset is also empty. Returning empty map.");
return new HashMap<>();
}
return fallbackData;
}
/**
* Reads a dataset from a CSV file.
*
* @param filePath Path to the CSV file.
* @return A Map representing the dataset, or null if an error occurs.
* @throws IOException If an I/O error occurs.
*/
private static Map<String, String> readDataset(String filePath) throws IOException {
Map<String, String> dataset = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 2) {
dataset.put(parts[0].trim(), parts[1].trim());
}
}
} catch (IOException e) {
System.err.println("Error reading dataset: " + e.getMessage());
return null;
}
return dataset;
}
public static void main(String[] args) {
String primaryPath = "primary_data.csv";
String backupPath = DEFAULT_FALLBACK_DATASET;
try {
Map<String, String> synchronizedData = syncDatasets(primaryPath, backupPath);
if (synchronizedData != null) {
System.out.println("Synchronized data: " + synchronizedData);
} else {
System.out.println("Synchronization failed.");
}
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Add your comment