天天看點

commons-csv讀取csv檔案

1 背景

實際工作中,很多資料都存在csv檔案中,使用 java語言開發的時候,有的時候需要讀取檔案,或者将csv檔案導入到資料庫中。commons-csv作為三方類庫,簡化了讀取操作

2 應用

2.1 引入pom

文章使用1.9.0版本

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

2.2 API應用

2.2.1 關于表頭的思考

什麼是表頭,注明每一列資料代表的含義,這個很重要

csv檔案有兩種關于表頭的應用,或者可以說玩法

csv檔案第一行是表頭

csv表頭放在其它檔案

2.2.2 csv檔案第一行是表頭

map就是一行資料 key是列名, value是具體的值,接下來你可以根據自己的業務處理了

File file = new File(csv);
  CSVFormat format = CSVFormat.DEFAULT.withHeader();
  InputStreamReader isr = new InputStreamReader(new FileInputStream(f), "UTF-8");
  CSVParser records = new CSVParser(isr, format);
  for (CSVRecord record : records) {
    Map<String, String> map = record.toMap();
  }      

2.2.3 csv表頭放在其它檔案

File file = new File(csv);
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader("表頭").parse(inputStreamReader);
for (CSVRecord csvRecord : records) {
  Map<String, String> map = csvRecord.toMap();                                         
}