Apache Commons CSV:用逗号读取值

时间:2016-03-21 11:16:51

标签: java csv opencsv

我正在将CSV文件转换为Java Bean。我需要将逗号保持在“”

中的值中

这是我的代码。

public static PPRCV convertContestToObj(String fileName) throws IOException {

    PPRCV pprcvHandler = PPRCVFactory.getPPRCVTable(fileName);

    CSVFormat csvFileFormat = CSVFormat.DEFAULT.newFormat(',').withEscape('"');

    List<PPRCV> pprcvs = new ArrayList<>();
    FileReader fileReader = new FileReader(fileName);

    CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);

    List<CSVRecord> csvRecords = csvFileParser.getRecords();

    for (CSVRecord csvRecord : csvRecords) {
        pprcvs.add(pprcvHandler.populateDynamicDetails(csvRecord));
    }

    return pprcvHandler;

}

示例CSV行:

7080001,XI,ProvinceX,TownX,BRGX,“SHOOL,BRGX”,“0054A,0055A,0055B,0055C”

我的DTO

private String precintCode;

private String regionName;

private String provinceName;

private String municipalityName;

private String districtName;

private String votingCenter;

private String precint;

我的预期输出应为

  

precintCode =“7080001”

     

regionName =“XI”

     

provinceName =“ProvinceX”

     

municipalityName =“TownX”

     

districtName =“BRGX”

     

votingCenter =“SCHOOL,BRGX”

     

precint =“0054A,0055A,0055B,0055C”

但实际输出是

  

precintCode =“7080001”

     

regionName =“XI”

     

provinceName =“ProvinceX”

     

municipalityName =“TownX”

     

districtName =“BRGX”

     

votingCenter =“”SCHOOL“

     

precint =“,BRGX,”0054A“

4 个答案:

答案 0 :(得分:1)

您需要withIgnoreSurroundingSpaces()选项。所有其他设置可以保留DEFAULT

    final Reader in = new StringReader("7080001, XI, ProvinceX, TownX, BRGX, \"SHOOL, BRGX\", \"0054A,0055A,0055B,0055C\" ");
    final CSVFormat csvFileFormat = CSVFormat.DEFAULT.withIgnoreSurroundingSpaces();

    for (CSVRecord record: csvFileFormat.parse(in)) {
        for (String field: record) {
            System.out.println("\"" + field + "\"");
        }
        System.out.println();
    }

输出

"7080001"
"XI"
"ProvinceX"
"TownX"
"BRGX"
"SHOOL, BRGX"
"0054A,0055A,0055B,0055C"

答案 1 :(得分:1)

我可以使用库中的 withQuote 函数来完成它。

{{1}}

答案 2 :(得分:0)

您是否已尝试使用CSVFormat.DEFAULT constant? - 它适用于符合RFC 4180的CSV文件。

答案 3 :(得分:0)

以下方法对我有效:

<?xml version='1.0' encoding='UTF-8'?> <LedgerImport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xml.datev.de/bedi/tps/ledger/v040" generating_system="DATEV manuell" generator_info="DATEV Musterdaten" version="4.0" xsi:schemaLocation="http://xml.datev.de/bedi/tps/ledger/v040 Belegverwaltung_online_ledger_import_v040.xsd"> <consolidate consolidatedAmount="1337.01"> <accountsPayableLedger> <bookingText>amazon</bookingText> <invoiceId>1</invoiceId> </accountsPayableLedger> </consolidate> </LedgerImport>

相关问题