CodexBloom - Programming Q&A Platform

Parsing CSV with Embedded Newlines in Java - Issues with OpenCSV Library

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
csv opencsv parsing Java

I'm testing a new approach and I'm having a hard time understanding After trying multiple solutions online, I still can't figure this out. I've been struggling with this for a few days now and could really use some help. I've looked through the documentation and I'm still confused about I'm trying to parse a CSV file using OpenCSV (version 5.4), but I'm encountering issues with rows that contain embedded newlines within quoted fields. My CSV format looks something like this: ``` "Name","Address" "John Doe","123 Main St\nApartment 4B" "Jane Smith","456 Elm St" ``` When I attempt to read this CSV, the library seems to split the address into two separate rows, resulting in: ``` Name,Address John Doe,123 Main St Apartment 4B Jane Smith,456 Elm St ``` I've tried using the `CSVReaderBuilder` with a custom `ICSVParser` but it doesn't seem to handle the newlines correctly. Here's the code I've used: ```java import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.ICSVParser; import com.opencsv.parser.CSVParserBuilder; import java.io.FileReader; import java.util.List; public class CsvParserExample { public static void main(String[] args) throws Exception { ICSVParser parser = new CSVParserBuilder().withSeparator(',').build(); CSVReader reader = new CSVReaderBuilder(new FileReader("data.csv")) .withCSVParser(parser) .build(); List<String[]> records = reader.readAll(); for (String[] record : records) { System.out.println(record[0] + " | " + record[1]); } reader.close(); } } ``` However, I'm still getting the unexpected output. The configuration for the parser seems correct as I have set the separator to a comma, but the handling of newlines doesn't seem to be working. Have I missed something in the configuration, or is there a better approach to handle CSV parsing with embedded newlines in quoted fields using OpenCSV? Any insights would be greatly appreciated! I'm working on a API that needs to handle this. What am I doing wrong? I'm working on a API that needs to handle this. Any ideas what could be causing this? My development environment is Linux. I recently upgraded to Java LTS.