opencsv解析csv文件

 

注意如果是UTF-8-BOM模式,第一行会有bom的头标识,请修改文件编码模式为UTF-8,否则第一列会为空

package com.ydd.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.opencsv.CSVParser;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.ydd.model.Persion;

/**
 * 	如果出现第一列读取不到的情况请修改编码模式为UTF-8, (UTF-8-BOM模式会丢失第一列)
 * @author pc1010
 */
public class CsvUtil {

	/**
	 * 解析csv文件并转成bean
	 * @param file  csv文件
	 * @param clazz 类
	 * @param    泛型
	 * @return 泛型bean集合
	 */
	public static  List getCsvData(File file, Class clazz) {
		try {
			List result = new ArrayList();
			InputStream fileInput = new FileInputStream(file);
			InputStreamReader in = new InputStreamReader(fileInput);
			HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy<>();
			strategy.setType(clazz);
			CsvToBean csvToBean = new CsvToBeanBuilder(in).withSeparator(CSVParser.DEFAULT_SEPARATOR).withThrowExceptions(false)
					.withMappingStrategy(strategy).build();
			Iterator iterator = csvToBean.iterator();
			while (iterator.hasNext()) {
				try {
					T t = iterator.next();
					result.add(t);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}

 

你可能感兴趣的:(Java8.0,Java)