Groovy Split CSV

后端 未结 2 972
半阙折子戏
半阙折子戏 2020-12-16 07:16

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         


        
2条回答
  •  遥遥无期
    2020-12-16 07:24

    Writing a csv parser is a tricky business.

    I would let someone else do the hard work, and use something like 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
    }
    

    Which prints:

    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}
    

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

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

    Which prints

    {abc,def}
    

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

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

    Then use it as above

提交回复
热议问题