Groovy学习笔记(1)读取CSV文件
|
??本篇分享讲展示如何在Groovy中读取CSV文件。
??以下的Groovy代码将具体展示如何使用Apache Commons CSV库来读取本地的CSV文件: //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 ''
}
在以上的Groovy代码中,我们使用java的io.File来读取本地文件,使用Apache Commons CSV库来具体处理CSV文件,使用CSV文件格式的RFC4180的标准,该标准具体说明可参考网址:https://tools.ietf.org/html/r... .我们先读取该CSV文件的表头,再读取该CSV文件的数据,最后按行输出其内容。
??本次分享到此结束,欢迎大家交流~~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

