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

Initial effort at rewriting writeCSV() to use openCSV calls

Currently doesn't leave content on the OutputStreamReader.
Need to debug.
parent 03fb253b
No related branches found
No related tags found
No related merge requests found
......@@ -6,6 +6,8 @@ package edu.unl.cse.csv_io;
import com.opencsv.CSVReaderHeaderAware;
import com.opencsv.CSVReaderHeaderAwareBuilder;
import com.opencsv.CSVWriterBuilder;
import com.opencsv.ICSVWriter;
import com.opencsv.exceptions.CsvValidationException;
import java.io.*;
......@@ -85,26 +87,32 @@ public class CSVReaderWriter {
}
static void placeCSVonStream(Collection<Map<String, String>> data, OutputStream outputStream) {
PrintStream writer = new PrintStream(outputStream);
Set<String> fieldNames = null;
int number_of_fields = 0;
ICSVWriter csvWriter = new CSVWriterBuilder(new OutputStreamWriter(outputStream)).build();
List<String[]> allLines = new LinkedList<>();
String[] fieldNames = getFieldNames(data);
int number_of_fields = fieldNames.length;
allLines.add(fieldNames);
for (Map<String, String> row : data) {
String[] values = new String[number_of_fields];
int field_number = 0;
if (fieldNames == null) {
fieldNames = row.keySet();
number_of_fields = fieldNames.size();
for (String field : fieldNames) {
writer.print(field);
writer.print(++field_number < number_of_fields ? "," : "\n");
String value = row.get(field);
values[field_number++] = value != null ? value : "";
}
allLines.add(values);
}
field_number = 0;
for (String field : fieldNames) {
String value = row.get(field);
writer.print(value != null ? value : "");
writer.print(++field_number < number_of_fields ? "," : "\n");
csvWriter.writeAll(allLines, false);
}
private static String[] getFieldNames(Collection<Map<String, String>> data) {
Set<String> fieldNames = new HashSet<>();
for (Map<String, String> row : data) {
fieldNames.addAll(row.keySet());
}
List<String> fieldList = new ArrayList<>(fieldNames);
String[] fieldArray = new String[fieldList.size()];
fieldArray = fieldList.toArray(fieldArray);
return fieldArray;
}
/* LEGACY METHODS */
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment