Java读取csv文件

1.导入csv依赖

<!--csv文件操作-->
        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>

2.CSV工具类(包含读取与写入两个方法)

package com.winsun.dataclean.utils;
 
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
 
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
 
 
/**
 *
 * @author laz
 * @since 2022-08-23
 */
public class ReadCsvFile {
 
 
    /**
     * 读取csv文件
     * @param filePath
     * @return
     */
    public static ArrayList<String[]> readCsvFile(String filePath){
        ArrayList<String[]> csvList = new ArrayList<String[]>();
        try {
            CsvReader reader = new CsvReader(filePath,',',Charset.forName("UTF-8"));
//          reader.readHeaders(); //跳过表头,不跳可以注释掉
 
            while(reader.readRecord()){
                //按行读取,并把每一行的数据添加到list集合
                csvList.add(reader.getValues());
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return csvList;
    }
 
 
    /**
     * 读取文件某列数据
     * @param filePath
     * @param rows
     * @return
     */
    public static ArrayList<String> readCsvFileRow(String filePath,int rows){
        ArrayList<String> csvList = new ArrayList<String>();
        try {
            CsvReader reader = new CsvReader(filePath,',',Charset.forName("UTF-8"));
          reader.readHeaders(); //跳过表头,不跳可以注释掉
 
            while(reader.readRecord()){
                //按行读取,并把每一行某列的数据添加到list集合
                String[] values = reader.getValues();
                csvList.add(values[rows]);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return csvList;
    }
 
    /**
     * 写入csv文件
     * @param filePath
     * @throws IOException
     */
    public static void writer(String filePath,ArrayList<String[]> contents) throws IOException {
 
        // 第一参数:新生成文件的路径 第二个参数:分隔符(不懂仔细查看引用百度百科的那段话) 第三个参数:字符集
        CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("UTF-8"));
 
        // 写表头和内容(这里将表头和数据放在一起,也可以分开处理)
        contents.forEach(content->{
            try {
                csvWriter.writeRecord(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
 
        // 关闭csvWriter
        csvWriter.close();
 
    }
 
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值