当前位置: 首页 > 工具软件 > openCSV > 使用案例 >

opencsv : 解析CSV

公孙弘深
2023-12-01

前言

  • opencsv 5.0

项目地址

http://opencsv.sourceforge.net

maven坐标

<dependency>
	<groupId>com.opencsv</groupId>
	<artifactId>opencsv</artifactId>
	<version>5.0</version>
</dependency>

用法

csv文件内容示例:

"48480","10","SCR,6-32X1/4',HX,TF,ZPS,TRI-PT","N7",""
"DTHG6","10","null","Z6-9",""
"1213C","11","SCR,6-32X1/4',FLH,MS,ZPS,CTSK","N4",""
"N6370","15","TOOL,SYRNG,THRMGRS,V2","H4",""

代码如下:

final CSVParser parser = new CSVParserBuilder().withSeparator(',').withIgnoreQuotations(false).build();
try (CSVReader csvReader = new CSVReaderBuilder(new FileReader("yourfile.csv")))
				.withSkipLines(1)
				.withCSVParser(parser)
				.build()){
	Iterator<String[]> iterator = csvReader.iterator();
	while (iterator.hasNext()) {
		String[] cols = iterator.next();
		this.log.debug(StringUtils.join(cols, "|"));
	}
} catch (Exception e) {
	this.log.error("parser error", e);
}

输出:

48480|10|SCR,6-32X1/4',HX,TF,ZPS,TRI-PT|N7| 
DTHG6|10|null|Z6-9| 
1213C|11|SCR,6-32X1/4',FLH,MS,ZPS,CTSK|N4| 
N6370|15|TOOL,SYRNG,THRMGRS,V2|H4| 
 类似资料: