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

相关推荐
Mcband1 天前
Apache Commons IO:文件流处理利器,让Java IO操作更简单
java·开发语言·apache
非极限码农2 天前
Apache Spark 上手指南(基于 Spark 3.5.0 稳定版)
大数据·spark·apache
ApachePulsar3 天前
Apache Pulsar vs. RabbitMQ:差异与比较
分布式·rabbitmq·apache
lifallen4 天前
从Apache Doris 学习 HyperLogLog
java·大数据·数据仓库·算法·apache
DolphinScheduler社区4 天前
# 3.1.8<3.2.0<3.3.1,Apache DolphinScheduler集群升级避坑指南
java·大数据·开源·apache·任务调度·海豚调度
lisanmengmeng5 天前
apache-tomcat 安装部署
java·tomcat·apache
Hello.Reader5 天前
Apache StreamPark 快速上手从一键安装到跑起第一个 Flink SQL 任务
sql·flink·apache
sanx185 天前
专业电竞体育数据与系统解决方案
前端·数据库·apache·数据库开发·时序数据库
光军oi5 天前
全栈开发杂谈————关于websocket若干问题的大讨论
java·websocket·apache
二饭10 天前
POI操作Docx的踩坑指南(一)
java·apache