4

I'm new to apache-commons-csv 1.6

I have a basic requirement to print csv file with every record in new line. Am trying to use CSVPrinter's println method. For some weird reason, the output file doesn't have any newline character. Everything is printed in one single line.

I have tried to open the output in Notepad++ and show the non-printable characters. There is no character between the records. Any help would be appreciated greatly. Thanks.

CSVPrinter csvPrinter = null;

if(delimiter != null && delimiter.length() > 0) {
    csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.newFormat(delimiter.charAt(0)).withHeader(header));
}else {
    csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.DEFAULT.withHeader(header));
}

for(Map<String,String> record : inputList) {
    List<String> valueList = new ArrayList<String>();
    for(String key : record.keySet()) {
        valueList.add(record.get(key));
    }
    System.out.println(valueList);
    csvPrinter.printRecord(valueList);
    csvPrinter.println();
}
csvPrinter.close();

Expected result:

id|type|value|key

4|excel|0|excel.sheet.no

5|excel|dd/MM/yyyy|excel.date.format

6|excel|0|excel.baserate.rownum

Actual result: id|type|value|key4|excel|0|excel.sheet.no5|excel|dd/MM/yyyy|excel.date.format6|excel|0|excel.baserate.rownum

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
thatsarunb4u
  • 53
  • 1
  • 6

3 Answers3

4

Don't use newFormat method if you don't want to override all delimiters

Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized with null/false.

If you want to add new line delimiter per record add withRecordSeparator

CSVFormat.newFormat(delimiter.charAt(0)).withHeader(header)).
 withRecordSeparator(System.getProperty("line.separator"));

Returns a new CSVFormat with the record separator of the format set to the specified character.

Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and "\r\n"

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Thanks a lot for the response. Now I understand why its not printing the newline. I have two issues after I made code changes. New code: csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.DEFAULT.withDelimiter(delimiter.charAt(0)).withHeader(header)); 1. Header is printed with double quotes. 2. There is an additional blank line at the end of the file. – thatsarunb4u Apr 10 '19 at 07:37
2

I have same problem changing withRecordSeparator does not helped. For workaround solution I'm printing new line directly like:

private static final char DELIMITER_CHAR = ',';

        try (CSVParser parser = CSVFormat.newFormat(DELIMITER_CHAR).withTrailingDelimiter(false)
                .withRecordSeparator('\n').parse(new InputStreamReader(new ByteArrayInputStream(bytes)));
             CSVPrinter printer = CSVFormat.newFormat(DELIMITER_CHAR).print(destinationFile, Charset.defaultCharset())) {
            for (CSVRecord record : parser) {
                try {
                    printer.printRecord(record);
                   // printer.println(); // TODO not working
                   printer.print('\n'); // work around solution 
                } catch (Exception e) {
                    throw new RuntimeException("Error at line " + parser.getCurrentLineNumber(), e);
                }
            }
            printer.flush();
        }
i.karayel
  • 4,377
  • 2
  • 23
  • 27
0

Update to the main answer of https://stackoverflow.com/a/55606621/373498

Since withRecordSeparator is deprecated, you should use .setRecordSeparator(System.getProperty("line.separator")) to define line breaks.

Example:

final CSVFormat csvFormat = CSVFormat.Builder
            .create()
            .setHeader(csvHeaders)
            .setDelimiter(";")
            .setQuoteMode(QuoteMode.ALL)
            .setRecordSeparator("\n") // unix line feed
            .setAutoFlush(true)
            .setEscape('"')
            .build();

 final StringWriter stringWriter = new StringWriter();
 try (CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat)) {
:
Huluvu424242
  • 756
  • 10
  • 25