Updated to use a Stream

This commit is contained in:
amdegregorio 2019-01-10 10:50:03 -05:00
parent 91f8c421c9
commit 81e2750ee0
2 changed files with 9 additions and 18 deletions

View File

@ -1,11 +1,8 @@
package com.baeldung.csv; package com.baeldung.csv;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriteCsvFileExample { public class WriteCsvFileExample {
public void writeLine(BufferedWriter writer, String[] data) throws IOException { public String convertToCSV(String[] data) {
StringBuilder csvLine = new StringBuilder(); StringBuilder csvLine = new StringBuilder();
for (int i = 0; i < data.length; i++) { for (int i = 0; i < data.length; i++) {
@ -15,7 +12,7 @@ public class WriteCsvFileExample {
csvLine.append(escapeSpecialCharacters(data[i])); csvLine.append(escapeSpecialCharacters(data[i]));
} }
writer.write(csvLine.toString()); return csvLine.toString();
} }
public String escapeSpecialCharacters(String data) { public String escapeSpecialCharacters(String data) {

View File

@ -3,12 +3,10 @@ package com.baeldung.csv;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.junit.Before; 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\"" }); dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
File csvOutputFile = new File(CSV_FILE_NAME); File csvOutputFile = new File(CSV_FILE_NAME);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvOutputFile))) { try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
for (Iterator<String[]> dataIterator = dataLines.iterator(); dataIterator.hasNext();) { dataLines.stream()
csvExample.writeLine(writer, dataIterator.next()); .map(csvExample::convertToCSV)
if (dataIterator.hasNext()) { .forEach(pw::println);
writer.newLine(); } catch (FileNotFoundException e) {
}
}
writer.flush();
} catch (IOException e) {
LOG.error("IOException " + e.getMessage()); LOG.error("IOException " + e.getMessage());
} }