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

Added code to write CSV file

parent be637096
No related branches found
No related tags found
No related merge requests found
......@@ -5,10 +5,8 @@
package edu.unl.cse.csv_io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.net.URL;
import java.util.*;
public class CSVReaderWriter {
......@@ -29,6 +27,47 @@ public class CSVReaderWriter {
return csvSet;
}
public static boolean writeCSV(String filename, Set<Map<String, String>> data) {
boolean wroteFile = true;
ClassLoader classLoader = CSVReaderWriter.class.getClassLoader();
URL resource = classLoader.getResource("csv/" + filename);
if (resource != null) {
File file = new File(resource.getPath());
try(OutputStream outputStream = new FileOutputStream(file)) {
PrintStream writer = new PrintStream(outputStream);
Set<String> fieldNames = null;
int number_of_fields = 0;
for (Map<String, String> row: data) {
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");
}
}
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");
}
}
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("Could not open " + filename + "; probably due to a bad pathname. " + fileNotFoundException);
wroteFile = false;
} catch (IOException ioException) {
System.err.println("Error opening " + filename + ". " + ioException);
wroteFile = false;
}
} else {
System.err.println("csv/" + filename + " not found. Cannot overwrite file unless it exists.");
wroteFile = false;
}
return wroteFile;
}
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));
......@@ -57,6 +96,9 @@ public class CSVReaderWriter {
public static void main(String[] args) {
Set<Map<String, String>> demo = readCSV("demo.csv");
boolean success = writeCSV("out.csv", demo);
System.out.println(success ? "Wrote file!" : "Didn't write file");
/*
Set<String> fieldNames = null;
for (Map<String, String> row: demo) {
if (fieldNames == null) {
......@@ -68,5 +110,6 @@ public class CSVReaderWriter {
}
System.out.println();
}
*/
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment