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

相关推荐
wei_shuo13 分钟前
时序数据库 Apache IoTDB 实战:基于 Kubernetes 的部署运维全指南
apache·时序数据库·iotdb
阿眠16 小时前
vue3实现web端和小程序端个人签名
前端·小程序·apache
熊文豪1 天前
时序数据库选型指南 —— 为什么选择 Apache IoTDB?
apache·时序数据库·iotdb
lang201509281 天前
Apache Ignite 的 Pages Writes Throttling(页面写入节流)
apache
FreeBuf_2 天前
Apache CXF 漏洞曝光:存在拒绝服务与数据泄露双重风险
apache
星释2 天前
WAMP允许远程访问
php·apache·wamp
阿里云云原生2 天前
赠送 10 张三天通票,和我们来畅聊 CommunityOverCode Asia 2025
apache
阿里云云原生3 天前
Apache RocketMQ + “太乙” = 开源贡献新体验
apache·rocketmq
Rinleren3 天前
Apache部署
apache