Java Read CSV File In Java With OpenCSV library, int filed 属性为 int类型
sample2.csv
COUNTRY,CAPITAL,POPULATION
India,New Delhi, 100
People's republic of China,Beijing, 200
United States,Washington D.C., 300
Country2.java 中 population 为int类型:
package com.jiangge.csv.opencsvtest;
public class Country2 {
private String countryName;
private String capital;
private int population;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
JavaBeanMapWithCSV2.java
package com.jiangge.csv.opencsvtest;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.CsvToBean;
import au.com.bytecode.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
//sample2.csv
//COUNTRY,CAPITAL,POPULATION
//India,New Delhi, 100
//People's republic of China,Beijing, 200
//United States,Washington D.C., 300
public class JavaBeanMapWithCSV2 {
public static void main(String[] args) {
HeaderColumnNameTranslateMappingStrategy<Country2> strategy = new HeaderColumnNameTranslateMappingStrategy<Country2>();
strategy.setType(Country2.class);
Map<String, String> columnMapping = new HashMap<String, String>();
columnMapping.put("COUNTRY", "countryName"); //关联
columnMapping.put("CAPITAL", "capital"); //关联
columnMapping.put("POPULATION", "population"); //关联
strategy.setColumnMapping(columnMapping);
List<Country2> list = null;
String csvFilename = "C:\\sample2.csv";
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFilename));
// CSVReader reader = new CSVReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("C:\\sample.csv")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
CsvToBean<Country2> csvToBean = new CsvToBean<Country2>();
list = csvToBean.parse(strategy, reader);
for (Object object : list) {
Country2 country = (Country2) object;
System.out.println(country.getCountryName() + " " + country.getPopulation());
}
}
}
输出结果:
India 100
People's republic of China 200
United States 300
可以看我另外一篇博文:
http://blog.csdn.net/xiaowanggedege/article/details/17711945