Java使用Apache Commons高效處理CSV文件的操作指南
1、簡(jiǎn)述
在 Java 開(kāi)發(fā)中,CSV(Comma-Separated Values,逗號(hào)分隔值)是一種常見(jiàn)的數(shù)據(jù)存儲(chǔ)格式,廣泛用于數(shù)據(jù)交換和簡(jiǎn)單的存儲(chǔ)任務(wù)。Apache Commons CSV 是 Apache 提供的一個(gè)輕量級(jí)庫(kù),專注于簡(jiǎn)化 CSV 文件的解析和生成,支持多種 CSV 格式,如 Excel、RFC 4180、MySQL 等。
本文將介紹 Commons CSV 的核心功能,并通過(guò)多個(gè)詳細(xì)的使用示例展示其在 CSV 文件解析和生成中的強(qiáng)大功能。
2、為什么選擇 Commons CSV?
- 輕量級(jí):無(wú)需龐大的依賴,功能集中。
- 支持多種格式:兼容 Excel、RFC 4180、Tab 分隔等格式。
- 簡(jiǎn)單易用:API 設(shè)計(jì)清晰,易于上手。
- 靈活性高:支持自定義分隔符、自定義換行符等多種配置。
在使用 Commons CSV之前,需要添加其依賴。以下是 Commons CSV 的 Maven 依賴:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.10.0</version> </dependency>
3、使用樣例
Spring Boot 集成 Commons CSV 常見(jiàn)的使用樣例,以下舉例供參考:
3.1 寫(xiě)入 CSV 文件
Commons CSV 同樣支持輕松生成 CSV 文件:
package com.lm.csv.example; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; import java.io.IOException; public class CsvWriterExample { public static void main(String[] args) throws IOException { // 創(chuàng)建 CSV 文件 try (FileWriter writer = new FileWriter("e:\\csv\\output.csv"); CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Name", "Age", "Email"))) { printer.printRecord("1", "Alice", "25", "alice@example.com"); printer.printRecord("2", "Bob", "30", "bob@example.com"); printer.printRecord("3", "Charlie", "35", "charlie@example.com"); } } }
3.2 使用自定義分隔符
如果需要自定義分隔符(例如分號(hào) :),可以通過(guò)配置實(shí)現(xiàn):
package com.lm.csv.example; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import java.io.FileWriter; public class CustomDelimiterExample { public static void main(String[] args) throws Exception { try (FileWriter writer = new FileWriter("e:\\csv\\custom_delimiter.csv"); CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT .withHeader("ID", "Name", "Age", "Email") .withDelimiter(':'))) { printer.printRecord("1", "Diana", "40", "diana@example.com"); printer.printRecord("2", "Eve", "22", "eve@example.com"); } } }
3.3 解析嵌套引號(hào)或特殊字符
CSV 文件中可能包含嵌套引號(hào)或特殊字符(如換行符),Commons CSV 能輕松解析:
package com.lm.csv.example; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import java.io.StringReader; public class SpecialCharacterExample { public static void main(String[] args) throws Exception { String csvData = "ID,Name,Notes\n" + "1,\"John\",\"Loves coding\nand teaching\"\n" + "2,\"Jane\",\"Enjoys reading\""; try (CSVParser parser = CSVFormat.DEFAULT .withFirstRecordAsHeader() .parse(new StringReader(csvData))) { parser.forEach(record -> { String id = record.get("ID"); String name = record.get("Name"); String notes = record.get("Notes"); System.out.printf("ID: %s, Name: %s, Notes: %s%n", id, name, notes); }); } } }
3.4 使用枚舉映射字段
對(duì)于字段定義明確的 CSV 文件,可以使用枚舉來(lái)避免硬編碼字段名稱:
package com.lm.csv.example; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.FileReader; public class EnumFieldExample { enum Header { ID, Name, Age, Email } public static void main(String[] args) throws Exception { try (FileReader reader = new FileReader("e:\\csv\\output.csv"); CSVParser parser = CSVFormat.DEFAULT .withFirstRecordAsHeader() .parse(reader)) { for (CSVRecord record : parser) { String id = record.get(Header.ID); String name = record.get(Header.Name); String age = record.get(Header.Age); String email = record.get(Header.Email); System.out.printf("ID: %s, Name: %s, Age: %s, Email: %s%n", id, name, age, email); } } } }
4、總結(jié)
Apache Commons CSV 是處理 CSV 文件的高效工具,無(wú)論是解析復(fù)雜的 CSV 數(shù)據(jù)還是生成自定義格式的 CSV 文件,都能提供簡(jiǎn)潔高效的解決方案。
優(yōu)點(diǎn):
- 輕量級(jí)且易于使用。
- 豐富的功能支持,如自定義分隔符、多格式支持。
- 提供全面的 CSV 文件讀取和寫(xiě)入功能。
適用場(chǎng)景:
- 數(shù)據(jù)導(dǎo)入和導(dǎo)出。
- 數(shù)據(jù)轉(zhuǎn)換和清洗。
- 作為應(yīng)用程序中的輕量級(jí)數(shù)據(jù)庫(kù)。
- 通過(guò)本文的示例,希望你能夠快速掌握 Commons CSV 的使用方法,并靈活應(yīng)用于實(shí)際項(xiàng)目中!
以上就是Java使用Apache Commons高效處理CSV文件的操作指南的詳細(xì)內(nèi)容,更多關(guān)于Java Apache Commons處理CSV的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringCloud筆記(Hoxton)Netflix之Ribbon負(fù)載均衡示例代碼
這篇文章主要介紹了SpringCloud筆記HoxtonNetflix之Ribbon負(fù)載均衡,Ribbon是管理HTTP和TCP服務(wù)客戶端的負(fù)載均衡器,Ribbon具有一系列帶有名稱的客戶端(Named?Client),對(duì)SpringCloud?Ribbon負(fù)載均衡相關(guān)知識(shí)感興趣的朋友一起看看吧2022-06-06Eclipse安裝Aptana插件(注意對(duì)應(yīng)版本問(wèn)題)
這篇文章主要為大家詳細(xì)介紹了Eclipse安裝Aptana插件的相關(guān)資料,特別注意對(duì)應(yīng)版本問(wèn)題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02springboot實(shí)現(xiàn)單文件和多文件上傳
這篇文章主要為大家詳細(xì)介紹了springboot實(shí)現(xiàn)單文件和多文件上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀
這篇文章主要介紹了Java中的synchronized和ReentrantLock的區(qū)別詳細(xì)解讀,synchronized是Java內(nèi)建的同步機(jī)制,所以也有人稱其為 IntrinsicLocking,它提供了互斥的語(yǔ)義和可見(jiàn)性,當(dāng)一個(gè)線程已經(jīng)獲取當(dāng)前鎖時(shí),其他試圖獲取的線程只能等待或者阻塞在那里,需要的朋友可以參考下2024-01-01Java如何實(shí)現(xiàn)將類文件打包為jar包
這篇文章主要介紹了Java如何實(shí)現(xiàn)將類文件打包為jar包,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06