簡體   English   中英

如何從 groovy (Jenkins) 中的兩個文件中寫入一個文件?

[英]How to write one file from two files in groovy (Jenkins)?

我有兩個 *.hex 文件(可以像 ASCII 文件一樣處理)從 Jenkinsfile groovy 管道構建腳本生成。 成功構建后,作業工作區中有以下文件:

  1. a.十六進制
  2. b.十六進制

我需要的是 c.hex,這只是兩個 a.hex 和 b.hex 粘在一個文件中。

在 C 中,它看起來像這樣:

static void mergeIntelHexFiles(const char* aFile, const char* bFile, const char* mergedFile)
{
  FILE* readFileA  = fopen(aFile, "r");
  FILE* readFileB = fopen(bFile, "r");
  if (   (NULL != readFileA  )
      && (NULL != readFileB ))
  {
    FILE* writeFile = fopen(mergedFile, "w");
    if (NULL != writeFile)
    {
      char lineBuffer[MAX_PATH_LEN];

      while (NULL != fgets(lineBuffer, MAX_PATH_LEN, readFileA ))
      {
        if (NULL == strstr(lineBuffer, ":00000001FF"))
        { // it is not the last line of the file
          fputs(lineBuffer, writeFile); // copy the line without modification
        }
      }

      while (NULL != fgets(lineBuffer, MAX_PATH_LEN, readFileB ))
      {
        fputs(lineBuffer, writeFile); // copy the line without modification
      }

      fclose(writeFile);
    }
    fclose(readFileA);
    fclose(readFileB);
  }
}

這只會將 a.hex 的每一行復制到 c.hex 中,然后將 b.hex 的每一行復制到 c.hex 中。

但是在 Jenkins Groovy 我不知道該怎么做……

我只能找到像這樣的簡單示例的文檔

那么問題來了,groovy中如何將兩個文件合二為一呢?

Groovy 在文件 class 上有一些很好的重載方法,以及允許您將 append 內容寫入文件的重載“<<”運算符。 只需一行代碼即可輕松解決您的用例:

new File("c.hex") <<  new File("a.hex").text <<  new File("b.hex").text

在您的評論中,您詢問如何合並文件並刪除 a.hex 的最后一行。 它需要更多的代碼,但仍然很容易完成:

def cHex = new File("c.hex")
def lines = new File("a.hex").readLines()
lines.eachWithIndex { String line, int idx -> if(idx < lines.size() - 1) cHex << line << '\n' }
cHex << new File("b.hex").text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM