1

I must use the library simpleflatmapper and I can't find a way to simply write in a csv file a List<String[]> with this library. I can parse (without blankline) and stock in a List<String[]> :

FileReader file = new FileReader("file.csv");
Iterator<String[]> parser = CsvParser.separator(',').quote('\"').iterator(file);
List<String[]> lines = new ArrayList<String[]>();
String[] line;
while(parser.hasNext()) {
    line = parser.next();
    if (line[0].length() != 0) {
        lines.add(line);
    }
}
FileWriter fw = new FileWriter("copy_file.csv");
........

But I found no way to write a new csv file with the data of List<String[]> lines. I'm pretty sure it's possible but there's no enough appropriate documentation. In short, I need help!

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
YannickN.fr
  • 328
  • 2
  • 6
  • 18

2 Answers2

2

After a discussion with the library's author, it appears that the ideal code for this case is to use CsvCellWriter (when we don't know in advance the number of columns to write, in fact if we don't have the header) instead of CsvWriter because CsvWriter needs to know in advance the structure of the csv file to write; lines is a List<String[]>

The Maven dependency:

<groupId>org.simpleflatmapper</groupId>
<artifactId>sfm-csv</artifactId>
<version>3.18.3</version>

import org.simpleflatmapper.csv.*;
import org.simpleflatmapper.csv.impl.writer.CsvCellWriter;
..........
FileWriter writer = new FileWriter("new_file.csv");
CsvCellWriter cellWriter = CsvCellWriter.DEFAULT_WRITER.separator(',').quote('"');
lines.forEach ( strs ->  {
try {
    if (strs.length > 0) {
        cellWriter.writeValue(strs[0], writer);
        for (int i = 1; i < strs.length; i++) {
           cellWriter.nextCell(writer);
           cellWriter.writeValue(strs[i], writer);
        }
       }
    cellWriter.endOfRow(writer);
} catch (IOException e) {e.printStackTrace();}
} );
writer.close();

This code allows to write identically the data of the list because we can chose the separator, the quote and eventually other options. Moreover this library seems to be convenient and quick enough to parse csv files.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
YannickN.fr
  • 328
  • 2
  • 6
  • 18
1

From the front page of the official documentation:

CsvWriter.CsvWriterDSL<String[]> dsl = CsvWriter.from(String[].class)
                                                .columns("a[0]", "a[1]", "a[2]")
                                                .skipHeaders();

try (FileWriter fileWriter = new FileWriter(file)) {
    CsvWriter<String[]> writer = dsl.to(fileWriter);
    lines.forEach(CheckedConsumer.toConsumer(writer::append));
}

I assumed that each String[] has at least three elements - columns("a[0]", "a[1]", "a[2]"). Otherwise, an ArrayIndexOutOfBoundsException will occur.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142