1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. public class RecordImporter {
  9. public static List<Map<String, String>> importRecords(String filePath) {
  10. List<Map<String, String>> records = new ArrayList<>();
  11. Map<String, String> header = new HashMap<>();
  12. try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
  13. String line = br.readLine(); // Read the header line
  14. if (line != null) {
  15. String[] headers = line.split(","); // Assuming comma-separated values
  16. for (String headerText : headers) {
  17. header.put(headerText.trim(), ""); // Initialize header map
  18. }
  19. } else {
  20. System.err.println("File is empty.");
  21. return records; // Return empty list if file is empty
  22. }
  23. while ((line = br.readLine()) != null) {
  24. String[] values = line.split(","); // Assuming comma-separated values
  25. if (values.length != header.size()) {
  26. System.err.println("Skipping line due to incorrect number of fields: " + line);
  27. continue; // Skip lines with incorrect number of fields
  28. }
  29. Map<String, String> record = new HashMap<>();
  30. for (int i = 0; i < header.size(); i++) {
  31. record.put(header.keySet().toArray(new String[0])[i], values[i]);
  32. }
  33. records.add(record);
  34. }
  35. } catch (IOException e) {
  36. System.err.println("Error reading file: " + e.getMessage());
  37. return new ArrayList<>(); // Return empty list on error
  38. }
  39. return records;
  40. }
  41. public static void main(String[] args) {
  42. // Example usage (replace with your file path)
  43. String filePath = "records.csv";
  44. List<Map<String, String>> importedRecords = importRecords(filePath);
  45. for (Map<String, String> record : importedRecords) {
  46. System.out.println(record);
  47. }
  48. }
  49. }

Add your comment