diff options
author | 2023-06-15 18:21:32 +0200 | |
---|---|---|
committer | 2023-06-15 18:21:32 +0200 | |
commit | 550888891f9da7eeb6afd83f496e31340e617f78 (patch) | |
tree | bf405797e7bd6b92d6391490c0b04569fa0a5803 | |
parent | 7b101fbf9de9919ddaad93f14f41d5004a0666f8 (diff) | |
download | csv-utils-550888891f9da7eeb6afd83f496e31340e617f78.tar.gz csv-utils-550888891f9da7eeb6afd83f496e31340e617f78.zip |
Add the new parse() method
-rw-r--r-- | src/main/java/it/alessandroiezzi/csv/CSVParser.java | 48 |
1 files changed, 48 insertions, 0 deletions
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<T> { 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<T> cls) { this.csvFile = csvFile; this.cls = cls; @@ -43,6 +51,46 @@ public class CSVParser<T> { return this; } + public List<T> parse() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(csvFile))) { + List<T> 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<T, String> 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<Map<String, String>> parseAsMap() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(csvFile)); List<Map<String, String>> records = new ArrayList<>(); |