??本篇分享讲展示如何在Groovy中读取CSV文件。
??我们要读取的CSV文件foo.csv的内容如下:
??Groovy代码如下:
//import packages
import java.io.File
// use @Grab() to download CSV package
@Grab(‘org.apache.commons:commons-csv:1.2‘)
import static org.apache.commons.csv.CSVFormat.RFC4180
// get csv file
def file = new File(‘/home/vagrant/foo.csv‘)
// read the header of csv file
def header = RFC4180.withHeader()
.parse(file.newReader())
.getHeaderMap().keySet()
// print the header
for(item in header){
print item
print ‘\t‘
}
println ‘‘
// read records and handle data by row
RFC4180.withHeader()
.parse(file.newReader())
.iterator().each { record ->
def cols = record.mapping.keySet()
for(item in cols){
print record.get(item)
print ‘\t‘
}
println ‘‘
}
输出的内容如下:
??本次分享到此结束,欢迎大家交流~~
原文地址:https://www.cnblogs.com/jclian91/p/8669197.html
时间: 2024-10-07 13:41:18