Reputation: 11
How can I deal with breaklines in column in CSVParser for Java.
Reader in = new FileReader(csvFile);
csvParser = CSVFormat.DEFAULT.withFirstRecordAsHeader().withQuote('"').withDelimiter(';').withEscape('\\').withRecordSeparator('\n').parse(in);
columnList = csvParser.getHeaderNames();
for(CSVRecord record: csvParser.getRecords()) {
rows.add(prepareRow(record));
}
Here is my options, but when I have something like this I can't run it, because it ignore " " as escape
1042377;"Test";"Test";Test;611945;311.12;2;https://example.com/1.jpg;"
"
1042377;"Test";"Test";Test;611945;311.12;2;https://example.com/2.jpg;"
"
it should create 2 rows, but it create more rows. How can I fix it? Edit for send code
it works fine when I don't have strings which have only 1 line, but it's problematic when I have string with multiple rows
Upvotes: 1
Views: 407
Reputation: 11
I found problem. It was, because I had \" in my data. I'm not sure, but I couldn't fix it. I changed it in csv file
Upvotes: 0
Reputation: 191
I can't reproduce your issue, the parser seems to be working fine. This code:
CSVParser csvParser = CSVFormat.DEFAULT
// .withFirstRecordAsHeader()
.withQuote('"')
.withDelimiter(';')
.withEscape('\\')
.withRecordSeparator('\n')
.parse(new InputStreamReader(new ByteArrayInputStream(in.getBytes())));
for(CSVRecord record: csvParser.getRecords()){
//replace new line char with a visible "\n"
record.forEach(field -> System.out.println(field.replace("\n", "\\n")));
System.out.println("End of record.");
}
Prints this output:
1042377
Test
Test
Test
611945
311.12
2
https://example.com/1.jpg
\n \n \n \n
End of record.
1042377
Test
Test
Test
611945
311.12
2
https://example.com/2.jpg
\n \n \n \n
End of record.
As you can see, it parses 2 rows with 9 columns each.
I am working with version 1.7 of org.apache.commons:commons-csv.
Note: I've commented .withFirstRecordAsHeader()
because you don't have headers.
Upvotes: 1