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

相关推荐
hopsky1 天前
2025 年 Apache DolphinScheduler 案例精选
apache
oMcLin2 天前
如何在 CentOS 7 上通过调优 Apache Tomcat 配置,提高高并发电商网站的性能?
centos·tomcat·apache
talenteddriver2 天前
java: JAVA静态方法细节
java·前端·apache
oMcLin4 天前
Debian 10 系统中高并发下 Apache 进程崩溃问题:如何通过调整 ulimit 与配置优化修复
运维·debian·apache
Par@ish5 天前
【网络安全】Apache StreamPipes 严重漏洞使攻击者可夺取管理员控制权
安全·web安全·apache
oMcLin5 天前
Ubuntu 22.04 配置 Apache 反向代理时无法访问后端应用:Nginx 与 Apache 配置冲突排查
nginx·ubuntu·apache
xiaoliuliu123456 天前
Apache JMeter 2.9 简单上手教程(附下载包)
jmeter·apache
DigitalOcean7 天前
Ubuntu/Debian VPS 上 Apache Web 服务器的完整配置教程
ubuntu·apache
java_logo7 天前
Apache Flink Docker 容器化部署指南
docker·flink·apache·apache flink·apache flink部署·flink部署文档·flink部署教程
彭于晏Yan7 天前
Apache Kafka使用
kafka·apache