Search code examples
javacsvunivocity

Changing order of comment section in CSV file using univocity


I am using univocity CSV parser to export my contents to CSV file. Here is my expected CSV file output,

#Comment Section-1
#Comment Section-2
Header-1,Header2,Header3
Data-1,data-2,data-3

But while exporting the contents to CSV file i am getting below format,

Header-1,Header2,Header3
#Comment Section-1
#Comment Section-2
Data-1,data-2,data-3

How do i move the comment section to top in univocity CSV parser lib ?


Solution

  • This should work:

        //let's write to a String to make this easy to test
        StringWriter out = new StringWriter();
    
        CsvWriterSettings settings = new CsvWriterSettings();
        //set headers
        settings.setHeaders("a", "b", "c");
        //automatically write headers when the first data row is written
        settings.setHeaderWritingEnabled(true);
    
        CsvWriter writer = new CsvWriter(out, settings);
        //write comment
        writer.commentRow("lalala");
    
        //write data rows
        writer.writeRow("1", "3", "6");
        writer.writeRow("3", "1", "1");
    
        writer.close();
    
        //print output
        System.out.println(out);
    

    The output produced is:

    #lalala
    a,b,c
    1,3,6
    3,1,1
    

    Hope this helps.