Search code examples
javacsvsimpleflatmapper

How to write a List<String[]> in a csv file with simpleflatmapper?


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!


Solution

  • 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.