我正在将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”
投票中心=“学校,BRGX”
precint =“ 0054A,0055A,0055B,0055C”
但是实际的输出是这个
precintCode =“ 7080001”
regionName =“ XI”
provinceName =“ ProvinceX”
MunicipalityName =“ TownX”
districtName =“ BRGX”
tingryCenter =“”学校“
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"