diff --git a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java index fd3678d2c5..e1237481b1 100644 --- a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java +++ b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java @@ -1,11 +1,8 @@ package com.baeldung.csv; -import java.io.BufferedWriter; -import java.io.IOException; - public class WriteCsvFileExample { - public void writeLine(BufferedWriter writer, String[] data) throws IOException { + public String convertToCSV(String[] data) { StringBuilder csvLine = new StringBuilder(); for (int i = 0; i < data.length; i++) { @@ -15,7 +12,7 @@ public class WriteCsvFileExample { csvLine.append(escapeSpecialCharacters(data[i])); } - writer.write(csvLine.toString()); + return csvLine.toString(); } public String escapeSpecialCharacters(String data) { diff --git a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java index 4ac84f939d..e30ec0818c 100644 --- a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java @@ -3,12 +3,10 @@ package com.baeldung.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; -import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.junit.Before; @@ -73,15 +71,11 @@ public class WriteCsvFileExampleUnitTest { dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" }); File csvOutputFile = new File(CSV_FILE_NAME); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvOutputFile))) { - for (Iterator dataIterator = dataLines.iterator(); dataIterator.hasNext();) { - csvExample.writeLine(writer, dataIterator.next()); - if (dataIterator.hasNext()) { - writer.newLine(); - } - } - writer.flush(); - } catch (IOException e) { + try (PrintWriter pw = new PrintWriter(csvOutputFile)) { + dataLines.stream() + .map(csvExample::convertToCSV) + .forEach(pw::println); + } catch (FileNotFoundException e) { LOG.error("IOException " + e.getMessage()); }