簡體   English   中英

使用 Apache 解決 CSV 文件中的無效數據

[英]Resolving invalid data in CSV file with Apache Commons

使用apache commons庫解析CSV數據遇到錯誤

java.lang.IllegalStateException: IOException reading next record: java.io.IOException: 
(line 46196) invalid char between encapsulated token and delimiter

我正在使用如下設置:

try {
    File csvInput = getLatestFilefromDir(CSV_PATH);
    reader = new FileReader(csvInput);

    final CSVFormat csvFormat = CSVFormat.Builder.create()
            .setHeader(HEADERS)
            .setDelimiter(';')
            .setQuote('"')
            .setEscape('\\')
            .setSkipHeaderRecord(true)
            .build();

    Iterable<CSVRecord> csvRecords = csvFormat.parse(reader);

    for (CSVRecord csvRecord : csvRecords) {
        // processing
    }
} catch (Exception e) {
    log.error("Error retrieving CSV data.");
    e.printStackTrace();
}

由於錯誤表明數據有一些缺陷,無效條目:

"TABLE_NAME";"ATTRIBUTE";"VALUE"
"SWAP_LEG_TYPE";"SWAP_LEG_TYPE_DESC";"The payments (PAY or RECEIVE) of this \"Leg\" are based on the yield linked to a specific equity or an index. (or to the actual market price of the equity or the index ???)"
"CNTPTY_TYPE";"CNTPTY_TYPE_DESC";"With Local Government we mean the so called \Regional Governments or Local Authorities\\" (RGLA) as defined by the EBA (European Banking Authority).\""

更改數據是我無法控制的。 假設反斜杠用於 escaping 引號,如在其他示例中一樣,在這種情況下使用不當並使其進入 CSV 文件,希望應該有

...Authorities\ \" (RGLA)...

有沒有辦法在解析之前替換字符串? 或者我可以做些什么來擴展CSVFormat構建器以接受此類數據?

我正在考慮讀取整個輸入的簡單方法,只需為\替換字符串\\因為這是百萬行中唯一的實例,但這似乎是錯誤的。

這是一個稍微修改過的原始版本,應該可以解決您的問題, setQuote(null)可以發揮所有作用。

    final CSVFormat csvFormat = CSVFormat.Builder.create()
            .setHeader(HEADERS)
            .setDelimiter(';')
            .setQuote(null)
            .setEscape('\\')
            .setSkipHeaderRecord(true)
            .build();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM