BAEL-2499 Write to CSV in Java - updated (#6135)
* example code for Article How to Write to a CSV File in Java * Updated to use a Stream * Updated to use Streams in convertToCSV for BAEL-2499
This commit is contained in:
parent
7397ac956c
commit
0bfa50825b
|
@ -1,18 +1,14 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class WriteCsvFileExample {
|
||||
|
||||
public String convertToCSV(String[] data) {
|
||||
StringBuilder csvLine = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
if (i > 0) {
|
||||
csvLine.append(",");
|
||||
}
|
||||
csvLine.append(escapeSpecialCharacters(data[i]));
|
||||
}
|
||||
|
||||
return csvLine.toString();
|
||||
return Stream.of(data)
|
||||
.map(this::escapeSpecialCharacters)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public String escapeSpecialCharacters(String data) {
|
||||
|
|
|
@ -65,7 +65,7 @@ public class WriteCsvFileExampleUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedWriter_whenWriteLine_thenOutputCreated() {
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
|
Loading…
Reference in New Issue