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

相关推荐
SelectDB技术团队8 小时前
Apache Doris 自动分区:如何应对分布式环境下的复杂并发挑战|Deep Dive
分布式·apache
StarRocks_labs21 小时前
StarRocks 4.0:让 Apache Iceberg 数据真正 Query-Ready
apache·数据湖·shuffle·starrocks 4.0·query-ready
武子康1 天前
大数据-154 Apache Druid 架构与组件职责全解析 版本架构:Coordinator/Overlord/Historical 实战
大数据·后端·apache
老罗-Mason2 天前
Apache Flink运行环境搭建
python·flink·apache
HashData酷克数据2 天前
Apache Cloudberry 孵化报告(202508-202510)
apache
迦蓝叶3 天前
Apache Jena:利用 SPARQL 查询与推理机深度挖掘知识图谱
java·数据挖掘·apache·知识图谱·查询·知识挖掘·推理机
JosieBook3 天前
【数据库】Apache IoTDB数据库在大数据场景下的时序数据模型与建模方案
数据库·apache·iotdb
SeaTunnel4 天前
结项报告完整版 | Apache SeaTunnel支持metalake开发
apache
迦蓝叶4 天前
Apache Jena 知识图谱持久化:选择适合你的存储方案
人工智能·开源·apache·知识图谱·持久化·存储·jena
q***98524 天前
【保姆级教程】apache-tomcat的安装配置教程
java·tomcat·apache