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

placeCSVonStream() now correctly leaves content on the stream

parent 19ad5c18
No related branches found
No related tags found
No related merge requests found
/* /*
* CSV Reader/Writer, copyright (c) 2019 Christopher A. Bohn, bohn@unl.edu. * CSV Reader/Writer, copyright (c) 2019-2020 Christopher A. Bohn, bohn@unl.edu.
*/ */
package edu.unl.cse.csv_io; package edu.unl.cse.csv_io;
import com.opencsv.CSVReaderHeaderAware; import com.opencsv.CSVReaderHeaderAware;
import com.opencsv.CSVReaderHeaderAwareBuilder; import com.opencsv.CSVReaderHeaderAwareBuilder;
import com.opencsv.CSVWriterBuilder; import com.opencsv.CSVWriter;
import com.opencsv.ICSVWriter;
import com.opencsv.exceptions.CsvValidationException; import com.opencsv.exceptions.CsvValidationException;
import java.io.*; import java.io.*;
...@@ -86,8 +85,9 @@ public class CSVReaderWriter { ...@@ -86,8 +85,9 @@ public class CSVReaderWriter {
return wroteFile; return wroteFile;
} }
static void placeCSVonStream(Collection<Map<String, String>> data, OutputStream outputStream) { static void placeCSVonStream(Collection<Map<String, String>> data, OutputStream outputStream) throws IOException {
ICSVWriter csvWriter = new CSVWriterBuilder(new OutputStreamWriter(outputStream)).build(); OutputStreamWriter writer = new OutputStreamWriter(outputStream);
CSVWriter csvWriter = new CSVWriter(writer);
List<String[]> allLines = new LinkedList<>(); List<String[]> allLines = new LinkedList<>();
String[] fieldNames = getFieldNames(data); String[] fieldNames = getFieldNames(data);
int number_of_fields = fieldNames.length; int number_of_fields = fieldNames.length;
...@@ -102,6 +102,7 @@ public class CSVReaderWriter { ...@@ -102,6 +102,7 @@ public class CSVReaderWriter {
allLines.add(values); allLines.add(values);
} }
csvWriter.writeAll(allLines, false); csvWriter.writeAll(allLines, false);
writer.close();
} }
private static String[] getFieldNames(Collection<Map<String, String>> data) { private static String[] getFieldNames(Collection<Map<String, String>> data) {
......
...@@ -128,7 +128,7 @@ public class CSVReaderWriterTest { ...@@ -128,7 +128,7 @@ public class CSVReaderWriterTest {
// We probably should test malformed CSVs, but this is good enough for students' starter code // We probably should test malformed CSVs, but this is good enough for students' starter code
@Test @Test
public void testWriting2x3CSV() { public void testWriting2x3CSV() throws IOException {
// Input // Input
String[] headers = {"header1", "header2"}; String[] headers = {"header1", "header2"};
String[][] rows = {{"datum1", "datum2"}, {"datum3", "datum4"}}; String[][] rows = {{"datum1", "datum2"}, {"datum3", "datum4"}};
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment