thatsarunb4u
thatsarunb4u

Reputation: 53

apache-commons-csv println method doesn't print newline in output

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

Upvotes: 4

Views: 3191

Answers (3)

Huluvu424242
Huluvu424242

Reputation: 765

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)) {
:

Upvotes: 0

i.karayel
i.karayel

Reputation: 4885

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();
        }

Upvotes: 2

Ori Marko
Ori Marko

Reputation: 58892

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"

Upvotes: 5

Related Questions