[英]Apache Commons CSV : Read Values with comma
I am converting CSV files to a Java Bean. 我正在将CSV文件转换为Java Bean。 I need to maintain the comma inside a value which is enclosed in "" .
我需要将逗号保留在“”内的值内。
Here is my code. 这是我的代码。
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;
}
Sample CSV line: 样本CSV行:
7080001, XI, ProvinceX, TownX, BRGX, "SHOOL, BRGX", "0054A,0055A,0055B,0055C" 7080001,XI,ProvinceX,TownX,BRGX,“ SHOOL,BRGX”,“ 0054A,0055A,0055B,0055C”
my DTO 我的DTO
private String precintCode;
private String regionName;
private String provinceName;
private String municipalityName;
private String districtName;
private String votingCenter;
private String precint;
My expected output should be 我的预期输出应该是
precintCode = "7080001"
precintCode =“ 7080001”
regionName = "XI"
regionName =“ XI”
provinceName = "ProvinceX"
provinceName =“ ProvinceX”
municipalityName = "TownX"
MunicipalityName =“ TownX”
districtName = "BRGX"
districtName =“ BRGX”
votingCenter = "SCHOOL, BRGX"
投票中心=“学校,BRGX”
precint = "0054A,0055A,0055B,0055C"
precint =“ 0054A,0055A,0055B,0055C”
However actual output is this 但是实际的输出是这个
precintCode = "7080001"
precintCode =“ 7080001”
regionName = "XI"
regionName =“ XI”
provinceName = "ProvinceX"
provinceName =“ ProvinceX”
municipalityName = "TownX"
MunicipalityName =“ TownX”
districtName = "BRGX"
districtName =“ BRGX”
votingCenter = ""SCHOOL"
tingryCenter =“”学校“
precint = " , BRGX,"0054A"
precint =“,BRGX,” 0054A“
You need the withIgnoreSurroundingSpaces()
optione here. 您在这里需要
withIgnoreSurroundingSpaces()
选项。 All other settings could be remain DEFAULT
. 所有其他设置可以保留为
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();
}
The output is 输出是
"7080001"
"XI"
"ProvinceX"
"TownX"
"BRGX"
"SHOOL, BRGX"
"0054A,0055A,0055B,0055C"
我可以使用库中的withQuote函数来做到这一点。
CSVFormat.EXCEL.newFormat(',').withQuote('"')
您是否已经尝试过使用CSVFormat.DEFAULT
常量 ?-它用于遵循RFC 4180的 CSV文件。
以下方法对我有用:
CSVFormat.EXCEL.withQuote('"')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.