Quotes appearing on CSV after concatnate fields using Groovy

后端 未结 1 847
渐次进展
渐次进展 2021-01-23 10:26

I\'m using groovy to concatenate two fields in CSV It\'s working ok except that the concatenated field is appearing with quotes.

Is there any way to resolve this?

<
相关标签:
1条回答
  • CSV is a more complicated file format than it would first appear. Fields can be optionally quoted which is what appears to be your problem.

    Most programming languages have a library that will parse CSV. In the case of groovy I'd recommend opencsv

    http://opencsv.sourceforge.net/

    The following example extends the example I created for your previous question.

    Example

    ├── build.xml
    ├── src
    │   └── file1.csv
    └── target
        └── file1.csv
    

    src/file1.csv

    "customer",deal
    "200000042",23
    "200000042",34
    "200000042",35
    "200000042",65
    

    target/file1.csv

    customer,deal,customer-deal
    200000042,23,200000042-23
    200000042,34,200000042-34
    200000042,35,200000042-35
    200000042,65,200000042-65
    

    build.xml

    <project name="demo" default="build" xmlns:ivy="antlib:org.apache.ivy.ant">
    
      <available classname="org.apache.ivy.Main" property="ivy.installed"/>
    
      <target name="build" depends="resolve">
        <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>
    
        <groovy>
          import com.opencsv.CSVReader
    
          ant.mkdir(dir:"target")
    
          new File("target/file1.csv").withWriter { writer ->
            new File("src/file1.csv").withReader { reader ->
              CSVReader csv = new CSVReader(reader);
    
              csv.iterator().each { row ->
                if (row.size() == 2) {
                  writer.println "${row[0]},${row[1]},${row[0]}-${row[1]}"
                }
              }
            }
          }
        </groovy>
      </target>
    
      <target name="resolve" depends="install-ivy"> 
        <ivy:cachepath pathid="build.path">
          <dependency org="org.codehaus.groovy" name="groovy-all" rev="2.4.7" conf="default"/>
          <dependency org="com.opencsv" name="opencsv" rev="3.8" conf="default"/>
        </ivy:cachepath>
      </target>
    
      <target name="install-ivy" unless="ivy.installed">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.4.0/ivy-2.4.0.jar"/>
        <fail message="Ivy has been installed. Run the build again"/>
      </target>
    
    </project>
    

    Notes:

    • Uses apache ivy to managed dependencies like groovy and opencsv
    • I included a test "row.size() == 2" to prevent empty rows throwing errors
    0 讨论(0)
提交回复
热议问题