Java Read CSV File In Java With OpenCSV library, int filed 属性为 int类型

3 篇文章 0 订阅

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值