如何用java解析CSV文件

Python015

如何用java解析CSV文件,第1张

思想:先获取csv文件路径,通过BufferedReader类去读该路径中的文件,使用readLine方法进行逐行读取。

注意:使用readLine方法后会自动转到下一行。因此在判断是否为空后得先将读取到的内容赋值给一变量,在循环中使用该变量即可。

public static void main(String[] args)

{

    File csv = new File("C:\\Users\\chenxumin\\Desktop\\Result.csv")  // CSV文件路径

    BufferedReader br = null

    try

    {

        br = new BufferedReader(new FileReader(csv))

    } catch (FileNotFoundException e)

    {

        e.printStackTrace()

    }

    String line = ""

    String everyLine = ""

    try {

            List<String> allString = new ArrayList<>()

            while ((line = br.readLine()) != null)  //读取到的内容给line变量

            {

                everyLine = line

                System.out.println(everyLine)

                allString.add(everyLine)

            }

            System.out.println("csv表格中所有行数:"+allString.size())

    } catch (IOException e)

    {

        e.printStackTrace()

    }

}

package com.test

import java.io.BufferedReader

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 TestImportCsv {

private InputStreamReader fr = null

private BufferedReader br = null

public TestImportCsv(String f) throws IOException {

fr = new InputStreamReader(new FileInputStream(f))

}

/**

* 解析csv文件 到一个list中 每个单元个为一个String类型记录,每一行为一个list。 再将所有的行放到一个总list中

*/

public List<List<String>>readCSVFile() throws IOException {

br = new BufferedReader(fr)

String rec = null// 一行

String str// 一个单元格

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

try {

// 读取一行

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

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) {

fr.close()

}

if (br != null) {

br.close()

}

}

return listFile

}

public static void main(String[] args) throws Throwable {

TestImportCsv test = new TestImportCsv("D:/test.csv")

List<List<String>>csvList = test.readCSVFile()

}

}