import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RecordImporter {
public static List<Map<String, String>> importRecords(String filePath) {
List<Map<String, String>> records = new ArrayList<>();
Map<String, String> header = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line = br.readLine(); // Read the header line
if (line != null) {
String[] headers = line.split(","); // Assuming comma-separated values
for (String headerText : headers) {
header.put(headerText.trim(), ""); // Initialize header map
}
} else {
System.err.println("File is empty.");
return records; // Return empty list if file is empty
}
while ((line = br.readLine()) != null) {
String[] values = line.split(","); // Assuming comma-separated values
if (values.length != header.size()) {
System.err.println("Skipping line due to incorrect number of fields: " + line);
continue; // Skip lines with incorrect number of fields
}
Map<String, String> record = new HashMap<>();
for (int i = 0; i < header.size(); i++) {
record.put(header.keySet().toArray(new String[0])[i], values[i]);
}
records.add(record);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
return new ArrayList<>(); // Return empty list on error
}
return records;
}
public static void main(String[] args) {
// Example usage (replace with your file path)
String filePath = "records.csv";
List<Map<String, String>> importedRecords = importRecords(filePath);
for (Map<String, String> record : importedRecords) {
System.out.println(record);
}
}
}
Add your comment