天下事有难易乎?为之,则难者亦易矣;不为,则易者亦难矣。

java使用CsvReader和CsvWriter对csv文件内容进行读取和写入操作

往事如烟 2353次浏览 0个评论
  • maven地址,直接放到pom.xml中
<!--csv处理-->
<dependency>
  <groupId>net.sourceforge.javacsv</groupId>
  <artifactId>javacsv</artifactId>
  <version>2.0</version>
</dependency>

工具类代码,如下:

package com.telelands.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * csv工具类
 */
public class CsvUtils {

    public static char separator = ',';

    public static void main(String[] args) {
        // 测试导出
//        String filePath = "F:\\data\\gd_xzl.csv";
        String filePath = "F:\\company_info.csv";
        // 读取CSV文件
        readCSV(filePath);
    }

    /**
     * 读取CSV文件
     * @param filePath:全路径名
     */
    public static List<String[]> readCSV(String filePath) {
        CsvReader reader = null;
        List<String[]> dataList = new ArrayList<>();
        try {
            //如果生产文件乱码,windows下用gbk,linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));
            // 读取表头
//            reader.readHeaders();
            // 逐条读取记录,直至读完
            while (reader.readRecord()) {
                dataList.add(reader.getValues());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
        return dataList;
    }

    /**
     * 生成CSV文件
     * @param dataList:数据集
     * @param filePath:全路径名
     */
    public static boolean createCSV(List<String[]> dataList, String filePath) throws Exception {
        boolean isSuccess = false;
        CsvWriter writer = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath, true);
            //如果生产文件乱码,windows下用gbk,linux用UTF-8
            writer = new CsvWriter(out, separator, Charset.forName("UTF-8"));
            for (String[] strs : dataList) {
                writer.writeRecord(strs);
            }
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return isSuccess;
    }


}

ITZOO版权所有丨如未注明 , 均为原创丨转载请注明来自IT乐园 ->java使用CsvReader和CsvWriter对csv文件内容进行读取和写入操作
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址