From 550888891f9da7eeb6afd83f496e31340e617f78 Mon Sep 17 00:00:00 2001 From: Alessandro Iezzi Date: Thu, 15 Jun 2023 18:21:32 +0200 Subject: Add the new parse() method --- .../java/it/alessandroiezzi/csv/CSVParser.java | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/main/java/it/alessandroiezzi/csv/CSVParser.java b/src/main/java/it/alessandroiezzi/csv/CSVParser.java index cf78c8c..eeb0ad9 100644 --- a/src/main/java/it/alessandroiezzi/csv/CSVParser.java +++ b/src/main/java/it/alessandroiezzi/csv/CSVParser.java @@ -27,6 +27,14 @@ public class CSVParser { throw new IllegalArgumentException("You need to define a constructor without parameters on " + cls.getName()); } + private T newInstance() { + try { + return cls.newInstance(); + } catch (InstantiationException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + public CSVParser(InputStream csvFile, Class cls) { this.csvFile = csvFile; this.cls = cls; @@ -43,6 +51,46 @@ public class CSVParser { return this; } + public List parse() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(csvFile))) { + List records = new ArrayList<>(); + String line; + String[] header = null; + + // Legge l'intestazione + if ((line = br.readLine()) != null) { + line = line.endsWith(separator) ? line.substring(0, line.length() - 1) : line; + header = line.replace("\"", "").split(separator); + } + + if (header == null || header.length == 0) + return records; + + // Procede a leggere i dati + while ((line = br.readLine()) != null) { + if (line.trim().isEmpty()) continue; /* Skip emtpy lines */ + + String[] values = line.replace("\"", "").split(separator, -1); + + if (values.length != header.length) { + throw new RuntimeException("Il numero di campi definiti nella testata non corrisponde con le colonne dei dati"); + } + + T data = newInstance(); + for (int j = 0; j < header.length; j++) { + BiConsumer func = mappers.get(header[j]); + if (func == null) continue; + func.accept(data, values[j]); + } + records.add(data); + } + + return records; + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + public List> parseAsMap() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(csvFile)); List> records = new ArrayList<>(); -- cgit v1.2.3