diff --git a/src/main/java/edu/unl/cse/csv_io/CSVReaderWriter.java b/src/main/java/edu/unl/cse/csv_io/CSVReaderWriter.java index 344b65ad00509cd02208f8c3bfcf244ccdf5bc2f..5af2dac2925917def88cdd30e9e69b1388ad1b64 100644 --- a/src/main/java/edu/unl/cse/csv_io/CSVReaderWriter.java +++ b/src/main/java/edu/unl/cse/csv_io/CSVReaderWriter.java @@ -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(); } + */ } }