summaryrefslogtreecommitdiff
path: root/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'src/main')
-rw-r--r--src/main/java/it/alessandroiezzi/csv/CSVUtils.java70
1 files changed, 70 insertions, 0 deletions
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 <aiezzi AT alessandroiezzi DOT it>
+ *
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+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<Map<String, String>> parse() throws IOException {
+ BufferedReader br = new BufferedReader(new InputStreamReader(csvFile));
+ List<Map<String, String>> 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<String, String> 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 = ";";
+}