通过 Groovy 附加现有的 CSV 文件

Appending an Existing CSV file via Groovy

下面的Groovy代码可以创建一个新的CSV文件(在本例中testfile.csv)并在CSV中写入JSON数据。 我不想创建新的 CSV 文件,只是想向现有 testfile.csv 文件添加(追加)几行而不覆盖文件。有人可以帮助更改以下代码以强制它附加文件而不是编写新文件吗?我听说过 StandardOpenOption.APPEND 但不知道该放在哪里。谢谢

import groovy.json.JsonSlurper;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import com.oracle.e1.common.OrchestrationAttributes;
import java.text.SimpleDateFormat;

HashMap < String, Object > main(OrchestrationAttributes orchAttr, HashMap inputMap) {
HashMap < String, Object > returnMap = new HashMap < String, Object > ();
returnMap.put("CSVComplete", "false");
// Write the view number after jsonIn.fs_DATABROWSE_
def jsonIn = new JsonSlurper().parseText(inputMap.get("Vendor Data"));
def jsonData = jsonIn.fs_DATABROWSE_GettingJsonDataFromSomewhere.data.gridData.rowset;

if (jsonData.size() == 0) {
  returnMap.put("CSVComplete", "empty");
  return returnMap;
}
def fileName = orchAttr.getTempFileName("testfile.csv");
returnMap.put("CSVOutFileName", fileName);
//class writer to write file def
def sw = new StringWriter();
//build the CSV writer with a header
//def csv = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader("Business Unit", "Document Number", "LT", "SUB","Amount","HardcodedTHREAD","ApprovedBudget","fromview003"));
  def csv = new CSVPrinter(sw, CSVFormat.DEFAULT); //No header
// create output file
fileCsvOut = new File(fileName);
def count=0;
// build the CSV
def an8Map = new ArrayList();
for (int i = 0; i < jsonData.size(); i++) {
  def businessunit = jsonData[i].table1_column1;
   if (an8Map.contains(businessunit)) {
     continue;
   }
   an8Map.add(businessunit);
   count++;
   csv.printRecord(businessunit, jsonData[i].table_column,  
                   jsonData[i].table1_column1, jsonData[i]. table1_column2, jsonData[i]. table1_column3, "Fixed text1 "Fixed text2", "Fixedtext3");
}
csv.close();

//writing csv to file
fileCsvOut.withWriter('UTF-8') {
  writer ->
   writer.write(sw.toString()) 
}
orchAttr.writeDebug(sw.toString());
returnMap.put("csv", sw.toString());
returnMap.put("CSVComplete", "true");
returnMap.put("CSVcount", Integer.toString(count));
return returnMap;
}

使用withWriterAppend代替withWriter

https://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html#withWriterAppend(java.lang.String,%20groovy.lang.Closure)