Skip to content

Handle comments

Although comments are not part of the CSV standard (per RFC 4180), many applications make use of comments in CSV files to provide additional information or to add context to the data.

A simple example of a CSV file with comments is shown below:

#This is a comment
field 1,field 2,field 3

A more complex example of a CSV file with comments is shown below. It shows how comments could be misinterpreted as part of a field if not handled correctly:

#This is a comment
field 1,"field 2 with a # character","field 3
#This is not a comment, but part of the third field that spans multiple lines"

Reading CSV files with comments

When reading comments, FastCSV provides flexibility in how comments are handled. You may ignore comments entirely by treating them as part of the data, skip them, or read and interpret them as comments. More information about the CommentStrategy enum can be found in the corresponding JavaDoc.

By default, FastCSV treats comments as part of the data to ensure that no data is lost and to maintain maximum compatibility with the RFC 4180 standard.

ExampleCsvReaderWithComments.java
package example;
import de.siegmar.fastcsv.reader.CommentStrategy;
import de.siegmar.fastcsv.reader.CsvReader;
/**
* Example for reading CSV data with comments.
*/
public class ExampleCsvReaderWithComments {
private static final String DATA = """
#line1
foo,bar
""";
public static void main(final String[] args) {
System.out.println("Reading data with no special treatment for comments:");
CsvReader.builder()
.ofCsvRecord(DATA)
.forEach(System.out::println);
System.out.println("Reading data while skipping comments:");
CsvReader.builder()
.commentStrategy(CommentStrategy.SKIP)
.ofCsvRecord(DATA)
.forEach(System.out::println);
System.out.println("Reading data while reading comments:");
CsvReader.builder()
.commentStrategy(CommentStrategy.READ)
.ofCsvRecord(DATA)
.forEach(rec -> {
if (rec.isComment()) {
System.out.println("Comment: " + rec.getField(0));
} else {
System.out.println("Record: " + rec);
}
});
}
}

You also find this source code example in the FastCSV GitHub repository.

Writing CSV files with comments

Writing comments to a CSV file is straightforward, as FastCSV takes care of any necessary escaping or line breaks.

ExampleCsvWriterWithComments.java
package example;
import de.siegmar.fastcsv.writer.CsvWriter;
/**
* Example for writing CSV data with comments (not part of the CSV standard).
*/
public class ExampleCsvWriterWithComments {
public static void main(final String[] args) {
CsvWriter.builder().toConsole()
.writeComment("A comment can be placed\nanywhere")
.writeRecord("field 1", "field 2", "field 3\n#with a line break")
.writeComment("in the CSV file");
}
}

You also find this source code example in the FastCSV GitHub repository.