Skip to content
Snippets Groups Projects
Commit be637096 authored by Christopher Bohn's avatar Christopher Bohn :thinking:
Browse files

Added code to parse CSV file

parent d20d0b42
Branches
Tags
No related merge requests found
/*
* CSV Reader/Writer, copyright (c) 2019 Christopher A. Bohn, bohn@unl.edu.
*/
package edu.unl.cse.csv_io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class CSVReaderWriter {
// this does not (yet) handle data elements that include commas and/or are surrounded by quotation marks
// use of ClassLoader.getResourceAsStream inspired by https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
// use of Map inspired by Python's csv module
private static final String DELIMTER = ",";
private static final char BYTE_ORDER_MARK = '\ufeff';
public static Set<Map<String, String>> readCSV(String filename) {
Set<Map<String, String>> csvSet = null;
ClassLoader classLoader = CSVReaderWriter.class.getClassLoader();
try(InputStream inputStream = classLoader.getResourceAsStream("csv/"+filename)) {
csvSet = parseCSV(inputStream);
} catch (IOException ioException) {
System.err.println("Error loading " + filename + ". " + ioException);
}
return csvSet;
}
private static Set<Map<String, String>> parseCSV(InputStream inputStream) throws IOException {
Set<Map<String, String>> csvSet = new HashSet<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
List<String> fieldNames = new ArrayList<>();
boolean header = true;
while ((line = reader.readLine()) != null) {
String[] elements = line.split(DELIMTER);
if (header) {
if (elements[0].charAt(0) == BYTE_ORDER_MARK) {
elements[0] = elements[0].substring(1); // remove text-encoding character sometimes added by Excel
}
fieldNames.addAll(Arrays.asList(elements));
header = false;
} else {
Map<String, String> row = new HashMap<>();
int column = 0;
for (String element: elements) {
row.put(fieldNames.get(column++), element);
}
csvSet.add(row);
}
}
return csvSet;
}
public static void main(String[] args) {
Set<Map<String, String>> demo = readCSV("demo.csv");
Set<String> fieldNames = null;
for (Map<String, String> row: demo) {
if (fieldNames == null) {
fieldNames = row.keySet();
}
for (String field: fieldNames) {
String value = row.get(field);
System.out.print(field + ":" + value + "\t");
}
System.out.println();
}
}
}
A, B, C, D
one,two,,three
four,,five,six
7,8,9,
,alpha,beta,gamma
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment