探秘 commons-csv:轻松搞定 CSV 文件操作

嘿,朋友!在 Java 开发中,处理 CSV(逗号分隔值)文件是一项常见的任务。Apache Commons CSV 库就是一个非常强大且易用的工具,它能让我们轻松地读取、写入和操作 CSV 文件。下面我就来详细给你讲讲 commons-csv 库的使用方法。

1. 引入 commons-csv 库

首先,你得把 commons-csv 库添加到你的项目中。如果你使用的是 Maven 项目,就在 pom.xml 文件里添加以下依赖:



<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.9.0</version>
</dependency>

2. 读取 CSV 文件

下面是使用 commons-csv 库读取 CSV 文件的示例代码:



import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class ReadCSVExample {
    public static void main(String[] args) {
        try {
            // 创建一个 Reader 对象,用于读取 CSV 文件
            Reader in = new FileReader("example.csv");

            // 使用 CSVFormat.DEFAULT 来解析 CSV 文件
            CSVParser parser = new CSVParser(in, CSVFormat.DEFAULT);

            // 遍历 CSV 文件的每一行记录
            for (CSVRecord record : parser) {
                // 遍历当前记录的每一个字段
                for (String field : record) {
                    System.out.print(field + "\t");
                }
                System.out.println();
            }

            // 关闭解析器
            parser.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("CSV 文件读取失败:" + e.getMessage());
        }
    }
}

代码解释

  • Reader in = new FileReader("example.csv");:创建一个 FileReader 对象,用于读取 example.csv 文件。

  • CSVParser parser = new CSVParser(in, CSVFormat.DEFAULT);:使用 CSVFormat.DEFAULT 来解析 CSV 文件,创建一个 CSVParser 对象。

  • for (CSVRecord record : parser):遍历 CSVParser 中的每一行记录,CSVRecord 表示一行数据。

  • for (String field : record):遍历当前记录的每一个字段,将其打印出来。

  • parser.close();:关闭 CSVParser,释放资源。

3. 写入 CSV 文件

接下来是使用 commons-csv 库写入 CSV 文件的示例代码:



import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class WriteCSVExample {
    public static void main(String[] args) {
        try {
            // 创建一个 Writer 对象,用于写入 CSV 文件
            Writer out = new FileWriter("output.csv");

            // 使用 CSVFormat.DEFAULT 来创建 CSVPrinter 对象
            CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT);

            // 写入表头
            printer.printRecord("Name", "Age", "City");

            // 写入数据行
            printer.printRecord("John", "25", "New York");
            printer.printRecord("Jane", "30", "Los Angeles");

            // 刷新并关闭 CSVPrinter
            printer.flush();
            printer.close();

            System.out.println("CSV 文件写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("CSV 文件写入失败:" + e.getMessage());
        }
    }
}

代码解释

  • Writer out = new FileWriter("output.csv");:创建一个 FileWriter 对象,用于写入 output.csv 文件。

  • CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT);:使用 CSVFormat.DEFAULT 来创建 CSVPrinter 对象,用于写入 CSV 文件。

  • printer.printRecord("Name", "Age", "City");:写入 CSV 文件的表头。

  • printer.printRecord("John", "25", "New York");:写入一行数据。

  • printer.flush(); printer.close();:刷新缓冲区并关闭 CSVPrinter,确保数据写入文件。

4. 自定义 CSV 格式

commons-csv 库还允许我们自定义 CSV 文件的格式,比如指定分隔符、引号字符等。以下是一个示例:



import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class CustomCSVFormatExample {
    public static void main(String[] args) {
        try {
            // 创建一个 Writer 对象,用于写入 CSV 文件
            Writer out = new FileWriter("custom_output.csv");

            // 自定义 CSV 格式,使用分号作为分隔符
            CSVFormat customFormat = CSVFormat.DEFAULT.withDelimiter(';');

            // 使用自定义格式创建 CSVPrinter 对象
            CSVPrinter printer = new CSVPrinter(out, customFormat);

            // 写入表头
            printer.printRecord("Name", "Age", "City");

            // 写入数据行
            printer.printRecord("John", "25", "New York");
            printer.printRecord("Jane", "30", "Los Angeles");

            // 刷新并关闭 CSVPrinter
            printer.flush();
            printer.close();

            System.out.println("自定义格式的 CSV 文件写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("CSV 文件写入失败:" + e.getMessage());
        }
    }
}

代码解释

  • CSVFormat customFormat = CSVFormat.DEFAULT.withDelimiter(';');:自定义 CSV 格式,使用分号作为分隔符。

  • CSVPrinter printer = new CSVPrinter(out, customFormat);:使用自定义格式创建 CSVPrinter 对象。

嘿,朋友,通过以上示例,你应该对 commons-csv 库在 CSV 文件操作方面有了一个基本的了解。赶紧动手试试吧,让你的 Java 程序也能轻松处理 CSV 文件!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五行星辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值