gpt4 book ai didi

java - Apache 共享 CSV : Read Values with comma

转载 作者:行者123 更新时间:2023-11-30 03:00:32 25 4
gpt4 key购买 nike

我正在将 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"

最佳答案

您需要此处的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"

关于java - Apache 共享 CSV : Read Values with comma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com