Apache Commons 读写 CSV 文件

文章目录

一、Maven 引入

xml 复制代码
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-csv -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.8</version>
        </dependency>

二、代码实现

java 复制代码
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ReadCsvNW {

    public static void main(String[] args) {
        try {
            InputStream inputStream = Files.newInputStream(Paths.get("D:\\Documents\\2024-06-16.zip"));
            ZipInputStream zis = new ZipInputStream(inputStream);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (!entry.isDirectory() && entry.getName().endsWith(".csv")) {

                    BufferedReader reader = new BufferedReader(new InputStreamReader(zis, "GBK"));
                    CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL.withFirstRecordAsHeader());

                    if (entry.getName().equals("hehe.csv")) {
                        for (CSVRecord record : csvParser) {
                            // 方式一:通过下角标获取值
                            System.out.println("数据行:" + record.get(5));
                            // 方式一:通过表头列名获取值
                            System.out.println("数据行:" + record.get("name"));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

参考:使用Apache Commons CSV在Java中读写CSV

相关推荐
zhojiew12 小时前
基于Pyspark对Apache Iceberg核心功能的使用实践
apache
SeaTunnel1 天前
AI 让 SeaTunnel 读源码和调试过时了吗?
大数据·数据库·人工智能·apache·seatunnel·数据同步
http阿拉丁神猫2 天前
ansible脚本解读
服务器·ansible·apache
小羊Yveesss2 天前
商家小程序外卖订单打印方案:云打印机对接、分单逻辑与模板配置实战
小程序·apache
@insist1232 天前
信息安全工程师-Apache/IIS安全增强与OWASP漏洞防护
安全·apache·软考·信息安全工程师·软件水平考试
Geek_Vison3 天前
如何借助小程序容器技术实现跨端APP的敏捷开发
小程序·apache·敏捷流程
Apache RocketMQ3 天前
Apache RocketMQ 5.0 架构解析:如何基于云原生架构支撑多元化场景
云原生·架构·apache·rocketmq·java-rocketmq
RingWu3 天前
微服务架构-全链路追踪:Apache SkyWalking
微服务·架构·apache
Donk_674 天前
高可用-Keepalived 解析
运维·服务器·apache
小羊Yveesss6 天前
门店小程序外卖配送搭建实战:配送对接、运费策略与多门店调度方案
小程序·apache