集册 Java实例教程 读取CSV文件

读取CSV文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

424
读取CSV文件


//package com.nowjava;

import java.io.BufferedReader;

/**
来 自 N o w J a v a . c o m
**/

import java.io.FileInputStream;


import java.io.IOException;

import java.io.InputStreamReader;


import java.util.ArrayList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class Main {


    public static List<List<String>> readCSVFile(String f,

            String charsetName) {

        InputStreamReader fr = null;/** N o  w  J a v a . c o m - 时  代  Java 提 供 **/

        BufferedReader br = null;


        String rec = null;// 

        String str;// ?

        List<List<String>> listFile = new ArrayList<List<String>>();

        try {

            fr = new InputStreamReader(new FileInputStream(f), charsetName);

            br = new BufferedReader(fr);

            // 

            while ((rec = br.readLine()) != null) {

                rec += ",";

                Pattern pCells = Pattern

                        .compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");

                Matcher mCells = pCells.matcher(rec);

                List<String> cells = new ArrayList<String>();// ?list

                // 

                while (mCells.find()) {

                    str = mCells.group();

                    str = str.replaceAll(

                            "(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");

                    str = str.replaceAll("(?sm)(\"(\"))", "$2");

                    cells.add(str);

                }

                listFile.add(cells);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (fr != null) {

                try {

                    fr.close();

            
展开阅读全文