Java解析CSV文件

阅读更多
package test.net.peter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.csvreader.CsvReader;

/**
 * 
 * 
 * 
 * @author  Peter.Qiu
 * @version  [Version NO, 2014-4-28]
 * @see  [Related classes/methods]
 * @since  [product/Modul version]
 */
public class CsvUtil {
    //读取csv文件
    public List readCsv(String filePath) throws Exception {
        List csvList = new ArrayList();
        if (isCsv(filePath)) {
            CsvReader reader = new CsvReader(filePath, ',', Charset.forName("utf-8"));
            //reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。
            while (reader.readRecord()) { //逐行读入除表头的数据
                csvList.add(reader.getValues());
            }
            reader.close();
        } else {
            System.out.println("此文件不是CSV文件!");
        }
        return csvList;
    }
    //判断是否是csv文件
    private boolean isCsv(String fileName) {
        return fileName.matches("^.+\\.(?i)(csv)$");
    }
    //方法测试
    public static void main(String[] args) throws Exception {
        String filepath = "d:/lucky_number_format.csv";
        CsvUtil su = new CsvUtil();
        List list = su.readCsv(filepath);
		for (int r = 0; r < list.size(); r++) {
			List prizeAmount = new ArrayList();
			List petternList = new ArrayList();
			for (int c = 0; c < list.get(r).length; c++) {
				String cell = list.get(r)[c];
				System.out.print(cell + "\t");
			}
			System.out.println();
		}
    }
}
对应的测试demo:http://download.csdn.net/detail/qiu_11/7271689

你可能感兴趣的:(Java解析CSV文件)