Apache Commons CSV:用逗号读取值 [英] Apache Commons CSV : Read Values with comma
问题描述
我正在将CSV文件转换为Java Bean.我需要将逗号保留在" 中的值内.
I am converting CSV files to a Java Bean. I need to maintain the comma inside a value which is enclosed in "".
这是我的代码.
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,省X,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"
precintCode = "7080001"
regionName ="XI"
regionName = "XI"
provinceName ="ProvinceX"
provinceName = "ProvinceX"
municipalityName ="TownX"
municipalityName = "TownX"
districtName ="BRGX"
districtName = "BRGX"
votingCenter =学校,BRGX"
votingCenter = "SCHOOL, BRGX"
precint ="0054A,0055A,0055B,0055C"
precint = "0054A,0055A,0055B,0055C"
但这是实际输出
precintCode ="7080001"
precintCode = "7080001"
regionName ="XI"
regionName = "XI"
provinceName ="ProvinceX"
provinceName = "ProvinceX"
municipalityName ="TownX"
municipalityName = "TownX"
districtName ="BRGX"
districtName = "BRGX"
votingCenter ="学校"
votingCenter = ""SCHOOL"
precint =,BRGX," 0054A"
precint = " , BRGX,"0054A"
推荐答案
我能够使用库中的 withQuote 函数来做到这一点.
I was able to do it using the withQuote function from the library.
CSVFormat.EXCEL.newFormat(',').withQuote('"')
这篇关于Apache Commons CSV:用逗号读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!