Groovy 拆分 CSV [英] Groovy Split CSV

查看:24
本文介绍了Groovy 拆分 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 csv 文件 (details.csv) 就像

I have a csv file (details.csv) like

ID,NAME,ADDRESS
1,"{foo,bar}","{123,mainst,ny}"
2,"{abc,def}","{124,mainst,Va}"
3,"{pqr,xyz}","{125,mainst,IL}"

当我使用时(注意:我上面还有其他闭包可以从目录中读取所有 csv 文件)

when I use (Note: I have other closure above this which reads all csv files from directory)

if(file.getName().equalsIgnoreCase("deatails.csv")) {
 input = new FileInputStream(file)
 reader = new BufferedReader(new InputStreamReader(input))
 reader.eachLine{line-> def cols = line.split(",")
 println cols.size() }

我得到的不是 3 码,而是 6 码

Instead of getting size 3 I am getting 6 with values

1
"{foo
bar}"
"{123
mainst
ny}"

spilt(",") 用逗号(,) 分割数据,但我希望我的结果为

spilt(",") is splitting data by comma(,) but I want my results as

1
"{foo,bar}"
"{123,mainst,ny}"

我该如何解决这个问题.请帮忙!谢谢

How can I fix this closure. Please help! Thanks

推荐答案

编写 csv 解析器是一项棘手的工作.

Writing a csv parser is a tricky business.

我会让其他人做一些艰苦的工作,并使用像 GroovyCsv

I would let someone else do the hard work, and use something like GroovyCsv

这里是如何用 GroovyCsv 解析它

Here is how to parse it with GroovyCsv

// I'm using Grab instead of just adding the jar and its
// dependencies to the classpath
@Grab( 'com.xlson.groovycsv:groovycsv:1.0' )
import com.xlson.groovycsv.CsvParser

def csv = '''ID,NAME,ADDRESS
1,"{foo,bar}","{123,mainst,ny}"
2,"{abc,def}","{124,mainst,Va}"
3,"{pqr,xyz}","{125,mainst,IL}"'''

def csva = CsvParser.parseCsv( csv )
csva.each {
  println it
}

打印:

ID: 1, NAME: {foo,bar}, ADDRESS: {123,mainst,ny}
ID: 2, NAME: {abc,def}, ADDRESS: {124,mainst,Va}
ID: 3, NAME: {pqr,xyz}, ADDRESS: {125,mainst,IL}

因此,要获取第二行的 NAME 字段,您可以执行以下操作:

So, to get the NAME field of the second row, you could do:

def csvb = CsvParser.parseCsv( csv )
println csvb[ 1 ].NAME

打印什么

{abc,def}

当然,如果 CSV 是文件,你可以这样做:

Of course, if the CSV is a File, you can do:

def csvc = new File( 'path/to/csv' ).withReader {
  CsvParser.parseCsv( it )
}

然后像上面一样使用

这篇关于Groovy 拆分 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆