From 2bd6b46c35d21040034b8ec3f87bd6eb1b83c541 Mon Sep 17 00:00:00 2001 From: Alessandro Iezzi Date: Tue, 10 May 2022 11:38:46 +0200 Subject: Initial commit --- src/main/java/it/alessandroiezzi/csv/CSVUtils.java | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/main/java/it/alessandroiezzi/csv/CSVUtils.java (limited to 'src/main') diff --git a/src/main/java/it/alessandroiezzi/csv/CSVUtils.java b/src/main/java/it/alessandroiezzi/csv/CSVUtils.java new file mode 100644 index 0000000..4f74030 --- /dev/null +++ b/src/main/java/it/alessandroiezzi/csv/CSVUtils.java @@ -0,0 +1,70 @@ +/* + * A simple CSV utility + * Copyright (C) 2022 Alessandro Iezzi + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package it.alessandroiezzi.csv; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CSVUtils { + private final InputStream csvFile; + + public CSVUtils(InputStream csvFile) { + this.csvFile = csvFile; + } + + public List> parse() throws IOException { + 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(COMMA_DELIMITER) ? line.substring(0, line.length() - 1) : line; + header = line.replace("\"", "").split(COMMA_DELIMITER); + } + + if (header == null || header.length == 0) + return records; + + // Procede a leggere i dati + while ((line = br.readLine()) != null) { + line = line.endsWith(COMMA_DELIMITER) ? line.substring(0, line.length() - 1) : line; + String[] values = line.replace("\"", "").split(COMMA_DELIMITER, -1); + + Map data = new HashMap<>(); + if (values.length != header.length) { + throw new RuntimeException("Il numero di campi definiti nella testata non corrisponde con le colonne dei dati"); + } + for (int j = 0; j < header.length; j++) { + data.put(header[j], values[j]); + } + records.add(data); + } + + return records; + } + + private final String COMMA_DELIMITER = ";"; +} -- cgit v1.2.3