我正在尝试使用 OpenCSV 解析 CSV 文件。其中一列以 YAML 序列化格式存储数据,并用引号引起来,因为其中可以包含逗号。它里面也有引号,所以通过加两个引号来转义。我可以在 Ruby 中轻松解析该文件,但使用 OpenCSV 我无法完全解析它。它是一个UTF-8编码的文件。
这是我的 Java 片段,它试图读取文件
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(csvFilePath), "UTF-8"), ',', '\"', '\\');
Run Code Online (Sandbox Code Playgroud)
以下是该文件中的 2 行。我猜第一行没有被正确解析,并且""[Fair Trade Certified]""
由于转义双引号而被分割。
1061658767,update,1196916,Product,28613099,Product::Source,"---
product_attributes:
-
- :name: Ornaments
:brand_id: 49120
:size: each
:alcoholic: false
:details: ""[Fair Trade Certified]""
:gluten_free: false
:kosher: false
:low_fat: false
:organic: false
:sugar_free: false
:fat_free: false
:vegan: false
:vegetarian: false
",,2015-11-01 00:06:19.796944,,,,,,
1061658768,create,,,28613100,Product::Source,"---
product_id:
retailer_id:
store_id:
source_id: 333790
locale: en_us
source_type: Product::PrehistoricProductDatum
priority: 1
is_definition:
product_attributes:
",,2015-11-01 00:06:19.927948,,,,,,
Run Code Online (Sandbox Code Playgroud)
解决方案是使用 RFC4180 兼容的 CSV 解析器,正如Paul所建议的。我使用了 OpenCSV 中的 CSVReader,但它不起作用,或者可能无法使其正常工作。
我使用了FastCSV,一个 RFC4180 CSV 解析器,它工作得非常顺利。
File file = new File(csvFilePath);
CsvReader csvReader = new CsvReader();
CsvContainer csv = csvReader.read(file, StandardCharsets.UTF_8);
for (CsvRow row : csv.getRows()) {
System.out.println(row.getFieldCount());
}
Run Code Online (Sandbox Code Playgroud)