天天看点

Java实现读取CSV

/**

  * 读取CSV文件

  *

  * @param file

  * @return

  */

 public static ArrayList<Map<String, String>> readCsv(String file)

 {

  logger.info("file:" + file);

  ArrayList<String[]> list = new ArrayList<String[]>();

  ArrayList<Map<String, String>> listMap = new ArrayList<Map<String, String>>();

  Map<String, String> map = new HashMap<String, String>();

  CsvReader reader = null;

  try

  {

   // 初始化CsvReader并指定列分隔符和字符编码

   reader = new CsvReader(file, ',', Charset.forName("GBK"));

   while (reader.readRecord())

   {

    // 读取每行数据以数组形式返回

    String[] str = reader.getValues();

    if (str != null && str.length > 0)

    {

     if (!str.toString().trim().equals(""))

     {

      list.add(str);

     }

    }

   }

   if (list.size() != 0 && list.size() != 1)

    for (int i = 1; i < list.size(); i++)

     map = new HashMap<String, String>();

     for (int j = 0; j < list.get(0).length; j++)

      if (j >= list.get(i).length)

      {

       break;

      }

      map.put(list.get(0)[j], list.get(i)[j]);

     listMap.add(map);

  }

  catch (FileNotFoundException e)

  catch (IOException e)

  finally

   if (reader != null)

    reader.close();

  return listMap;

 }

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.nio.charset.Charset;

import java.util.ArrayList;

import java.util.List;

Mc1081

import org.apache.log4j.Logger;

import com.csvreader.CsvReader;

import com.csvreader.CsvWriter;

 * CSV测试类

 *

 */

public class CSVTest {

 protected static Logger logger = Logger.getLogger(CSVTest.class);

 /**

 public static List<String[]> readCsv(String file) {

  List<String[]> list = new ArrayList<String[]>();

  try {

   while (reader.readRecord()) {

    if (str != null && str.length > 0) {

     if (str[0] != null && !"".equals(str[0].trim())) {

      System.out.println(str.length);

      System.out.println(str[1]);

  } catch (FileNotFoundException e) {

   logger.error(e.getMessage(), e);

  } catch (IOException e) {

  } finally {

   if (reader != null) {

  return list;

  * 写入CSV文件

 public static void writeCsv(List<String[]> content, String path) {

  CsvWriter writer = null;

   writer = new CsvWriter(path, ',', Charset.forName("GBK"));

   if(content != null && content.size() != 0) {

    for(String[] strArray : content) {

     writer.writeRecord(strArray);

   } else {

    // 做异常处理

   if(writer != null) {

    writer.close();

  * @param args

  * @throws Exception

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

  String readPath = "F:" + File.separator + "test" + File.separator + "muti-test.csv";

  String writePath = "F:" + File.separator + "test" + File.separator + "muti-test-output.csv";

  List<String[]> result = readCsv(readPath);

  for(String[] strArray : result) {

   for(String s : strArray) {

    System.out.print(s + ",");

   System.out.println();

  writeCsv(result, writePath);

  Thread.sleep(999999);

}